Skip to content

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

Add checkout and order promotions (#14696)

Iga Karbowiakb2a6e00945cf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d1e9439ff..af3f2310f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
- Drop `OrderBulkCreateInput.voucher` field. Use `OrderBulkCreateInput.voucherCode` instead. - #14553 by @zedzior
+- Add new `type` field to `PromotionCreateInput`, the field will be required from 3.20 - #14696 by @IKarbowiak, @zedzior
- Do not stack promotion rules within the promotion. Only the best promotion rule will be applied within the promotion. Previously discounts from all rules within the promotion that gives the best discount were applied to the variant's price - #15309 by @korycins
### GraphQL API
@@ -15,6 +16,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add taxes to undiscounted prices - #14095 by @jakubkuc
- Mark as deprecated: `ordersTotal`, `reportProductSales` and `homepageEvents` - #14806 by @8r2y5
- Add `identifier` field to App graphql object. Identifier field is the same as Manifest.id field (explicit ID set by the app).
+- Introduce `checkoutAndOrder` promotion rules that allow applying discounts during checkout calculations when the checkout meets certain conditions. - #14696 by @IKarbowiak, @zedzior
### Saleor Apps
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 5ad2781b20..04292fd558 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -16,6 +16,8 @@ from ..core.taxes import zero_money
from ..discount import DiscountValueType, VoucherType
if TYPE_CHECKING:
+ from decimal import Decimal
+
from ..channel.models import Channel
from .fetch import CheckoutInfo, CheckoutLineInfo, ShippingMethodInfo
@@ -26,7 +28,7 @@ def calculate_base_line_unit_price(
) -> Money:
"""Calculate line unit price including discounts and vouchers.
- The price includes sales, specific product and applied once per order
+ The price includes catalogue promotions, specific product and applied once per order
voucher discounts.
The price does not include the entire order discount.
"""
@@ -41,12 +43,13 @@ def calculate_base_line_unit_price(
def calculate_base_line_total_price(
line_info: "CheckoutLineInfo",
channel: "Channel",
+ include_voucher: bool = True,
) -> Money:
"""Calculate line total price including discounts and vouchers.
- The price includes sales, specific product and applied once per order
+ The price includes catalogue promotions, specific product and applied once per order
voucher discounts.
- The price does not include the entire order discount.
+ The price does not include order promotions and the entire order vouchers.
"""
variant = line_info.variant
currency = line_info.channel_listing.currency
@@ -62,7 +65,7 @@ def calculate_base_line_total_price(
discount_amount = Money(discount.amount_value, line_info.line.currency)
total_price -= discount_amount
- if line_info.voucher:
+ if include_voucher and line_info.voucher:
if not line_info.voucher.apply_once_per_order:
if line_info.voucher.discount_value_type == DiscountValueType.PERCENTAGE:
voucher_discount_amount = line_info.voucher.get_discount_amount_for(
@@ -116,7 +119,7 @@ def calculate_undiscounted_base_line_unit_price(
line_info: "CheckoutLineInfo",
channel: "Channel",
):
- """Calculate line unit price without including discounts and vouchers."""
+ """Calculate line unit price without discounts and vouchers."""
variant = line_info.variant
variant_price = variant.get_base_price(
line_info.channel_listing, line_info.line.price_override
@@ -127,6 +130,7 @@ def calculate_undiscounted_base_line_unit_price(
def base_checkout_delivery_price(
checkout_info: "CheckoutInfo",
lines: Optional[Iterable["CheckoutLineInfo"]] = None,
+ include_voucher: bool = True,
) -> Money:
"""Calculate base (untaxed) price for any kind of delivery method."""
currency = checkout_info.checkout.currency
@@ -135,7 +139,7 @@ def base_checkout_delivery_price(
is_shipping_voucher = (
checkout_info.voucher.type == VoucherType.SHIPPING
- if checkout_info.voucher
+ if include_voucher and checkout_info.voucher
else False
)
@@ -199,9 +203,9 @@ def base_checkout_total(
) -> Money:
"""Return the total cost of the checkout.
- The price includes sales, shipping, specific product and applied once per order
- voucher discounts.
- The price does not include the entire order discount.
+ The price includes catalogue promotions, shipping, specific product
+ and applied once per order voucher discounts.
+ The price does not include order promotions and the entire order vouchers.
"""
currency = checkout_info.checkout.currency
subtotal = base_checkout_subtotal(lines, checkout_info.channel, currency)
@@ -214,17 +218,19 @@ def base_checkout_subtotal(
checkout_lines: Iterable["CheckoutLineInfo"],
channel: "Channel",
currency: str,
+ include_voucher: bool = True,
) -> Money:
"""Return the checkout subtotal value.
- The price includes sales, specific product and applied once per order
+ The price includes catalogue promotions, specific product and applied once per order
voucher discounts.
- The price does not include the entire order discount.
+ The price does not include order promotions and the entire order vouchers.
"""
line_totals = [
calculate_base_line_total_price(
line,
channel,
+ include_voucher=include_voucher,
)
for line in checkout_lines
]
@@ -245,13 +251,13 @@ def checkout_total(
shipping_price = base_checkout_delivery_price(checkout_info, lines)
discount = checkout_info.checkout.discount
- # only entire_order discount with apply_once_per_order set to False is not
- # already included in the total price
- discount_not_included = (
- checkout_info.voucher.type == VoucherType.ENTIRE_ORDER
+ # order promotion discount and entire_order voucher discount with
+ # apply_once_per_order set to False are not included in the total price yet
+ discounted_object_promotion = bool(checkout_info.discounts)
+ discount_not_included = discounted_object_promotion or (
+ checkout_info.voucher
+ and checkout_info.voucher.type == VoucherType.ENTIRE_ORDER
and not checkout_info.voucher.apply_once_per_order
- if checkout_info.voucher
- else False
)
# Discount is subtracted from both gross and net values, which may cause negative
# net value if we are having a discount that covers whole price.
@@ -268,21 +274,44 @@ def apply_checkout_discount_on_checkout_line(
):
"""Calculate the checkout line price with discounts.
- Include the entire order voucher discount.
+ Include the entire order voucher discount or discount from order
+ promotion (this discount is applied only when voucher code is not set).
The discount amount is calculated for every line proportionally to
the rate of total line price to checkout total price.
"""
voucher = checkout_info.voucher
- if (
- not voucher
- or voucher.apply_once_per_order
+ if voucher and (
+ voucher.apply_once_per_order
or voucher.type in [VoucherType.SHIPPING, VoucherType.SPECIFIC_PRODUCT]
):
return line_total_price
+ if not voucher and not checkout_info.discounts:
+ return line_total_price
+
total_discount_amount = checkout_info.checkout.discount_amount
- line_total_price = line_total_price
- currency = checkout_info.checkout.currency
+ return _get_discounted_checkout_line_price(
+ checkout_line_info,
+ lines,
+ line_total_price,
+ total_discount_amount,
+ checkout_info.channel,
+ )
+
+
+def _get_discounted_checkout_line_price(
+ checkout_line_info: "CheckoutLineInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ line_total_price: Money,
+ total_discount_amount: "Decimal",
+ channel: "Channel",
+):
+ """Apply checkout discount on checkout line price.
+
+ Propagate the discount amount proportionally to total prices of items.
+ Ensure that the sum of discounts is equal to the discount amount.
+ """
+ currency = channel.currency_code
lines = list(lines)
@@ -299,7 +328,7 @@ def apply_checkout_discount_on_checkout_line(
lines_total_prices = [
calculate_base_line_total_price(
line_info,
- checkout_info.channel,
+ channel,
).amount
for line_info in lines
if line_info.line.id != checkout_line_info.line.id
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 492b934e1f..6507de8bf1 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -246,7 +246,7 @@ def _fetch_checkout_prices_if_expired(
charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)
should_charge_tax = charge_taxes and not checkout.tax_exemption
- create_or_update_discount_objects_from_promotion_for_checkout(lines)
+ create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)
if prices_entered_with_tax:
# If prices are entered with tax, we need to always calculate it anyway, to
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 8c8a3bf37b..c8a257cbc8 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -26,7 +26,7 @@ from ..core.tracing import traced_atomic_transaction
from ..core.transactions import transaction_with_commit_on_errors
from ..core.utils.url import validate_storefront_url
from ..discount import DiscountType, DiscountValueType
-from ..discount.models import NotApplicable, OrderLineDiscount
+from ..discount.models import CheckoutDiscount, NotApplicable, OrderLineDiscount
from ..discount.utils import (
get_sale_id,
increase_voucher_usage,
@@ -576,7 +576,7 @@ def _create_order(
tax_exemption=checkout_info.checkout.tax_exemption,
)
- _handle_checkout_discount(order, checkout)
+ _create_order_discount(order, checkout_info)
order_lines: list[OrderLine] = []
order_line_discounts: list[OrderLineDiscount] = []
@@ -1053,12 +1053,28 @@ def _handle_allocations_of_order_lines(
)
-def _handle_checkout_discount(order: "Order", checkout: "Checkout"):
- if checkout.discount:
- # store voucher as a fixed value as it this the simplest solution for now.
- # This will be solved when we refactor the voucher logic to use .discounts
- # relations
+def _create_order_discount(order: "Order", checkout_info: "CheckoutInfo"):
+ checkout = checkout_info.checkout
+ checkout_discount = checkout.discounts.first()
+ is_voucher_discount = checkout.discount and not checkout_discount
+ is_promotion_discount = (
+ checkout_discount and checkout_discount.type == DiscountType.ORDER_PROMOTION
+ )
+ if is_promotion_discount:
+ checkout_discount = cast(CheckoutDiscount, checkout_discount)
+ discount_data = model_to_dict(checkout_discount)
+ discount_data["promotion_rule"] = checkout_discount.promotion_rule
+ del discount_data["checkout"]
+ order.discounts.create(**discount_data)
+
+ if is_voucher_discount:
+ # Currently, we don't create `CheckoutDiscount` of type VOUCHER, so if there is
+ # discount on checkout, but not related `CheckoutDiscount`, we assume it is
+ # a voucher discount.
+ # Store voucher as a fixed value as it this the simplest solution for now.
+ # This will be solved when we refactor the voucher logic to use .discounts
+ # relations.
order.discounts.create(
type=DiscountType.VOUCHER,
value_type=DiscountValueType.FIXED,
@@ -1067,6 +1083,10 @@ def _handle_checkout_discount(order: "Order", checkout: "Checkout"):
translated_name=checkout.translated_discount_name,
currency=checkout.currency,
amount_value=checkout.discount_amount,
+ voucher=checkout_info.voucher,
+ voucher_code=checkout_info.voucher_code.code
+ if checkout_info.voucher_code
+ else None,
)
@@ -1199,7 +1219,7 @@ def _create_order_from_checkout(
)
# checkout discount
- _handle_checkout_discount(order, checkout_info.checkout)
+ _create_order_discount(order, checkout_info)
# lines
order_lines_info = _create_order_lines_from_checkout_lines(
@@ -1319,7 +1339,7 @@ def create_order_from_checkout(
# ensure that we are processing checkout on the current data.
checkout_lines, _ = fetch_checkout_lines(checkout, voucher=voucher)
checkout_info = fetch_checkout_info(
- checkout, checkout_lines, manager, voucher=voucher
+ checkout, checkout_lines, manager, voucher=voucher, voucher_code=code
)
assign_checkout_user(user, checkout_info)
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 2dd718a402..5a35eabdf9 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -27,7 +27,12 @@ if TYPE_CHECKING:
from ..account.models import Address, User
from ..channel.models import Channel
from ..discount.interface import VariantPromotionRuleInfo, VoucherInfo
- from ..discount.models import CheckoutLineDiscount, Voucher, VoucherCode
+ from ..discount.models import (
+ CheckoutDiscount,
+ CheckoutLineDiscount,
+ Voucher,
+ VoucherCode,
+ )
from ..plugins.manager import PluginsManager
from ..product.models import (
Collection,
@@ -74,6 +79,7 @@ class CheckoutInfo:
all_shipping_methods: list["ShippingMethodData"]
tax_configuration: "TaxConfiguration"
valid_pick_up_points: list["Warehouse"]
+ discounts: list["CheckoutDiscount"]
voucher: Optional["Voucher"] = None
voucher_code: Optional["VoucherCode"] = None
@@ -423,7 +429,7 @@ def fetch_checkout_info(
if shipping_channel_listings is None:
shipping_channel_listings = channel.shipping_method_listings.all()
- if not voucher:
+ if not voucher or not voucher_code:
voucher, voucher_code = get_voucher_for_checkout(
checkout, channel_slug=channel.slug
)
@@ -439,6 +445,7 @@ def fetch_checkout_info(
tax_configuration=tax_configuration,
all_shipping_methods=[],
valid_pick_up_points=[],
+ discounts=list(checkout.discounts.all()),
voucher=voucher,
voucher_code=voucher_code,
)
diff --git a/saleor/checkout/migrations/0063_checkout_base_total_and_subtotal.py b/saleor/checkout/migrations/0063_checkout_base_total_and_subtotal.py
new file mode 100644
index 0000000000..43a765a0ce
--- /dev/null
+++ b/saleor/checkout/migrations/0063_checkout_base_total_and_subtotal.py
@@ -0,0 +1,47 @@
+# Generated by Django 3.2.23 on 2024-01-03 08:53
+
+from decimal import Decimal
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "checkout",
+ "0062_update_checkout_last_transaction_modified_at_and_refundable",
+ ),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="base_subtotal_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="base_total_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkout
+ ALTER COLUMN base_subtotal_amount
+ SET DEFAULT 0;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkout
+ ALTER COLUMN base_total_amount
+ SET DEFAULT 0;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 1a94ab7ecd..be68eb11c9 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -111,6 +111,13 @@ class Checkout(models.Model):
net_amount_field="total_net_amount",
gross_amount_field="total_gross_amount",
)
+ # base price contains only catalogue discounts (does not contains voucher discount)
+ base_total_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ base_total = MoneyField(amount_field="base_total_amount", currency_field="currency")
subtotal_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
@@ -126,6 +133,15 @@ class Checkout(models.Model):
net_amount_field="subtotal_net_amount",
gross_amount_field="subtotal_gross_amount",
)
+ # base price contains only catalogue discounts (does not contains voucher discount)
+ base_subtotal_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ base_subtotal = MoneyField(
+ amount_field="base_subtotal_amount", currency_field="currency"
+ )
shipping_price_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.py
index db9159a73b..135595b3c4 100644
--- a/saleor/checkout/tests/test_base_calculations.py
+++ b/saleor/checkout/tests/test_base_calculations.py
@@ -10,6 +10,7 @@ from ..base_calculations import (
base_checkout_total,
calculate_base_line_total_price,
calculate_base_line_unit_price,
+ checkout_total,
)
from ..fetch import fetch_checkout_info, fetch_checkout_lines
@@ -885,3 +886,59 @@ def test_base_checkout_total_high_discount_on_shipping(
net = variant.get_price(channel_listing)
expected_price = net * checkout_with_item.lines.first().quantity
assert total == expected_price
+
+
+def test_base_checkout_total_order_discount(
+ checkout_with_item_and_order_discount, shipping_method
+):
+ # given
+ manager = get_plugins_manager(allow_replica=False)
+ checkout = checkout_with_item_and_order_discount
+ channel = checkout.channel
+
+ checkout.shipping_method = shipping_method
+ checkout_lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
+
+ # when
+ total = base_checkout_total(checkout_info, checkout_lines)
+
+ # then
+ variant = checkout.lines.first().variant
+ channel_listing = variant.channel_listings.get(channel=channel)
+ net = variant.get_price(channel_listing)
+ shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)
+ # order promotion discount shouldn't be included
+ expected_price = (
+ net * checkout.lines.first().quantity + shipping_channel_listings.price
+ )
+ assert total == expected_price
+
+
+def test_checkout_total_order_discount(
+ checkout_with_item_and_order_discount, shipping_method
+):
+ # given
+ manager = get_plugins_manager(allow_replica=False)
+ checkout = checkout_with_item_and_order_discount
+ channel = checkout.channel
+
+ checkout.shipping_method = shipping_method
+ checkout_lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
+
+ # when
+ total = checkout_total(checkout_info, checkout_lines)
+
+ # then
+ variant = checkout.lines.first().variant
+ channel_listing = variant.channel_listings.get(channel=channel)
+ net = variant.get_price(channel_listing)
+ shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)
+ # order promotion discount should be included
+ expected_price = (
+ net * checkout.lines.first().quantity
+ + shipping_channel_listings.price
+ - checkout.discount
+ )
+ assert total == expected_price
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index d94cc08520..a577ef0df6 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -334,6 +334,46 @@ def test_get_checkout_base_prices_no_charge_taxes_with_voucher(
assert line.total_price == checkout.total
+def test_get_checkout_base_prices_no_charge_taxes_with_order_promotion(
+ checkout_with_item_and_order_discount,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ discount_amount = checkout.discounts.first().amount_value
+
+ line = checkout.lines.first()
+ line.quantity = 7
+ line.save()
+
+ lines, _ = fetch_checkout_lines(checkout)
+ line_info = list(lines)[0]
+ variant = line_info.variant
+ product_price = variant.get_price(line_info.channel_listing)
+
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ _get_checkout_base_prices(checkout, checkout_info, lines)
+ checkout.save()
+ checkout.lines.bulk_update(
+ [line_info.line for line_info in lines],
+ [
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ "tax_rate",
+ ],
+ )
+
+ # then
+ line.refresh_from_db()
+ assert line.tax_rate == Decimal("0.0")
+
+ line_total = product_price.amount * line.quantity - discount_amount
+ assert line.total_price_gross_amount == line_total
+ assert checkout.total_gross_amount == line_total
+
+
@freeze_time("2020-12-12 12:00:00")
def test_fetch_checkout_data_webhooks_success(
plugins_manager,
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 3cc59f1b31..8fc408fb64 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -12,7 +12,13 @@ from prices import Money, TaxedMoney
from ...account.models import Address
from ...core.taxes import zero_money
-from ...discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
+from ...discount import (
+ DiscountType,
+ DiscountValueType,
+ RewardType,
+ RewardValueType,
+ VoucherType,
+)
from ...discount.interface import VariantPromotionRuleInfo
from ...discount.models import (
CheckoutLineDiscount,
@@ -327,6 +333,7 @@ def test_get_discount_for_checkout_value_entire_order_voucher(
valid_pick_up_points=[],
delivery_method_info=get_delivery_method_info(None, None),
all_shipping_methods=[],
+ discounts=[],
)
lines = [
CheckoutLineInfo(
@@ -491,6 +498,7 @@ def test_get_discount_for_checkout_value_specific_product_voucher(
valid_pick_up_points=[],
delivery_method_info=get_delivery_method_info(None, None),
all_shipping_methods=[],
+ discounts=[],
)
lines = [
CheckoutLineInfo(
@@ -606,6 +614,7 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
tax_configuration=channel_USD.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
manager = get_plugins_manager(allow_replica=False)
with pytest.raises(NotApplicable):
@@ -785,6 +794,7 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
tax_configuration=channel_USD.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
with pytest.raises(NotApplicable):
get_voucher_discount_for_checkout(manager, voucher, checkout_info, [], None)
@@ -892,6 +902,7 @@ def test_get_discount_for_checkout_shipping_voucher(
tax_configuration=channel_USD.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
discount = get_voucher_discount_for_checkout(
@@ -944,6 +955,7 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(
tax_configuration=channel_USD.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
discount = get_voucher_discount_for_checkout(
manager, voucher, checkout_info, [], None
@@ -990,6 +1002,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
tax_configuration=channel_USD.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
manager = get_plugins_manager(allow_replica=False)
with pytest.raises(NotApplicable):
@@ -1145,6 +1158,7 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
tax_configuration=channel_USD.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_checkout(
@@ -1270,7 +1284,7 @@ def test_recalculate_checkout_discount_with_sale(
def test_recalculate_checkout_discount_with_promotion(
checkout_with_voucher_percentage,
voucher_percentage,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
):
# given
checkout = checkout_with_voucher_percentage
@@ -1286,7 +1300,7 @@ def test_recalculate_checkout_discount_with_promotion(
line_info = lines[0]
reward_value = Decimal("1")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -1325,7 +1339,7 @@ def test_recalculate_checkout_discount_with_promotion(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
@@ -1352,6 +1366,86 @@ def test_recalculate_checkout_discount_with_promotion(
)
+def test_recalculate_checkout_discount_with_checkout_discount_voucher_not_applicable(
+ checkout_with_voucher_percentage,
+ voucher_percentage,
+ catalogue_promotion_without_rules,
+):
+ # given
+ checkout = checkout_with_voucher_percentage
+ channel = checkout.channel
+ voucher_percentage.channel_listings.filter(channel=channel).update(
+ min_spent_amount=100
+ )
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ line_info = lines[0]
+ reward_value = Decimal("1")
+ rule = catalogue_promotion_without_rules.rules.create(
+ name="Fixed promotion rule",
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(line_info.channel)
+
+ # when
+ recalculate_checkout_discount(manager, checkout_info, lines)
+
+ # then
+ assert checkout.discount_amount == reward_value
+ assert checkout.discount_name
+ assert not checkout.voucher_code
+
+
+def test_recalculate_checkout_discount_with_checkout_discount_voucher_added(
+ checkout_with_item_and_order_discount,
+ voucher_percentage,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ checkout_discount = checkout.discounts.first()
+ channel = checkout.channel
+ discount_value = voucher_percentage.channel_listings.get(
+ channel=channel
+ ).discount_value
+ checkout.voucher_code = voucher_percentage.code
+ checkout.save(update_fields=["voucher_code"])
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ recalculate_checkout_discount(manager, checkout_info, lines)
+
+ # then
+ line_info = lines[0]
+ total_price = (
+ line_info.variant.get_price(line_info.channel_listing) * line_info.line.quantity
+ )
+
+ checkout.refresh_from_db()
+ assert checkout.discount_amount == total_price.amount * discount_value / 100
+ assert checkout.discount_name == voucher_percentage.name
+ assert checkout.voucher_code
+ assert not checkout.discounts.all()
+ with pytest.raises(checkout_discount._meta.model.DoesNotExist):
+ checkout_discount.refresh_from_db()
+
+
def test_recalculate_checkout_discount_voucher_not_applicable(
checkout_with_voucher, voucher, channel_USD
):
@@ -1706,6 +1800,29 @@ def test_add_voucher_to_checkout_fail(
assert checkout_with_item.voucher_code is None
+def test_add_voucher_to_checkout_clears_order_promotion_discount(
+ checkout_with_item_and_order_discount, voucher
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ checkout_discount = checkout.discounts.first()
+ assert checkout.voucher_code is None
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ add_voucher_to_checkout(
+ manager, checkout_info, lines, voucher, voucher.codes.first()
+ )
+
+ # then
+ assert checkout.voucher_code == voucher.code
+ assert not checkout.discounts.all()
+ with pytest.raises(checkout_discount._meta.model.DoesNotExist):
+ checkout_discount.refresh_from_db()
+
+
def test_get_last_active_payment(checkout_with_payments):
# given
payment = Payment.objects.create(
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index 75330c8f23..f4f7b494cd 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -909,7 +909,7 @@ def test_create_order_product_on_promotion(
customer_user,
shipping_method,
app,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
):
# given
checkout = checkout_with_item_on_promotion
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 8af0a461d2..c1c0de6bed 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Optional, Union, cast
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models import prefetch_related_objects
from django.utils import timezone
from prices import Money
@@ -18,11 +19,12 @@ from ..core.utils.promo_code import (
promo_code_is_voucher,
)
from ..core.utils.translations import get_translation
-from ..discount import VoucherType
+from ..discount import DiscountType, VoucherType
from ..discount.interface import VoucherInfo, fetch_voucher_info
-from ..discount.models import NotApplicable, Voucher, VoucherCode
+from ..discount.models import CheckoutDiscount, NotApplicable, Voucher, VoucherCode
from ..discount.utils import (
- create_or_update_discount_objects_from_promotion_for_checkout,
+ create_discount_objects_for_catalogue_promotions,
+ create_discount_objects_for_order_promotions,
get_products_voucher_discount,
get_voucher_code_instance,
validate_voucher_for_checkout,
@@ -68,7 +70,7 @@ def invalidate_checkout_prices(
checkout = checkout_info.checkout
if recalculate_discount:
- create_or_update_discount_objects_from_promotion_for_checkout(lines)
+ create_discount_objects_for_catalogue_promotions(lines)
recalculate_checkout_discount(manager, checkout_info, lines)
checkout.price_expiration = timezone.now()
@@ -645,6 +647,8 @@ def recalculate_checkout_discount(
else:
remove_voucher_from_checkout(checkout)
+ create_discount_objects_for_order_promotions(checkout_info, lines, save=True)
+
def add_promo_code_to_checkout(
manager: PluginsManager,
@@ -731,18 +735,25 @@ def add_voucher_to_checkout(
)
checkout.discount = discount
- checkout.save(
- update_fields=[
- "voucher_code",
- "discount_name",
- "translated_discount_name",
- "discount_amount",
- "last_change",
- ]
- )
checkout_info.voucher = voucher
checkout_info.voucher_code = voucher_code
+ # delete discounts from order promotions as cannot be mixed with vouchers
+ with transaction.atomic():
+ checkout.save(
+ update_fields=[
+ "voucher_code",
+ "discount_name",
+ "translated_discount_name",
+ "discount_amount",
+ "last_change",
+ ]
+ )
+ CheckoutDiscount.objects.filter(
+ checkout=checkout_info.checkout,
+ type=DiscountType.ORDER_PROMOTION,
+ ).delete()
+
def remove_promo_code_from_checkout(
checkout_info: "CheckoutInfo", promo_code: str
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index 29a1b367ec..47cf8a7365 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -9,17 +9,18 @@ from django.db import connection
from ....account.utils import create_superuser
from ...utils.random_data import (
add_address_to_admin,
+ create_catalogue_promotions,
create_channels,
create_checkout_with_custom_prices,
create_checkout_with_preorders,
create_checkout_with_same_variant_in_multiple_lines,
create_gift_cards,
create_menus,
+ create_order_promotions,
create_orders,
create_page_type,
create_pages,
create_permission_groups,
- create_product_promotions,
create_products_by_schema,
create_shipping_zones,
create_staffs,
@@ -100,7 +101,9 @@ class Command(BaseCommand):
self.stdout.write(msg)
create_products_by_schema(self.placeholders_dir, create_images)
self.stdout.write("Created products")
- for msg in create_product_promotions(2):
+ for msg in create_catalogue_promotions(2):
+ self.stdout.write(msg)
+ for msg in create_order_promotions(2):
self.stdout.write(msg)
for msg in create_vouchers():
self.stdout.write(msg)
diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.py
index e38633578a..9120abd6f2 100644
--- a/saleor/core/tests/test_core.py
+++ b/saleor/core/tests/test_core.py
@@ -148,12 +148,23 @@ def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):
assert Order.objects.all().count() == how_many_orders
-def test_create_product_promotions(db):
+def test_create_catalogue_promotions(db):
how_many = 5
channel_count = 0
for _ in random_data.create_channels():
channel_count += 1
- for _ in random_data.create_product_promotions(how_many):
+ for _ in random_data.create_catalogue_promotions(how_many):
+ pass
+ assert Promotion.objects.all().count() == how_many
+ assert PromotionRule.objects.all().count() == how_many * 2
+
+
+def test_create_order_promotions(db):
+ how_many = 5
+ channel_count = 0
+ for _ in random_data.create_channels():
+ channel_count += 1
+ for _ in random_data.create_order_promotions(how_many):
pass
assert Promotion.objects.all().count() == how_many
assert PromotionRule.objects.all().count() == how_many * 2
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index b18ea11296..9ffdae1b66 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -55,6 +55,7 @@ from ...discount.models import (
)
from ...giftcard import events as gift_card_events
from ...giftcard.models import GiftCard, GiftCardTag
+from ...graphql.discount.enums import RewardTypeEnum
from ...menu.models import Menu, MenuItem
from ...order import OrderStatus
from ...order.models import Fulfillment, Order, OrderLine
@@ -828,7 +829,7 @@ def create_fake_order(max_order_lines=5, create_preorder_lines=False):
return order
-def create_fake_promotion():
+def create_fake_catalogue_promotion():
promotion = Promotion.objects.create(
name=f"Happy {fake.word()} day!",
)
@@ -871,6 +872,43 @@ def create_fake_promotion():
return promotion
+def create_fake_order_promotion():
+ promotion = Promotion.objects.create(
+ name=f"Happy {fake.word()} day!",
+ )
+ rules = PromotionRule.objects.bulk_create(
+ [
+ PromotionRule(
+ promotion=promotion,
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=random.choice([10, 20, 30, 40, 50]),
+ reward_type=RewardTypeEnum.SUBTOTAL_DISCOUNT.name,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"range": {"gte": "200"}}
+ }
+ },
+ ),
+ PromotionRule(
+ promotion=promotion,
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=random.choice([10, 20, 30, 40, 50]),
+ reward_type=RewardTypeEnum.SUBTOTAL_DISCOUNT.name,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"range": {"gte": "100"}}
+ }
+ },
+ ),
+ ]
+ )
+ channels = Channel.objects.all()
+ for rule in rules:
+ rule.channels.add(*channels)
+
+ return promotion
+
+
def create_users(user_password, how_many=10):
for _ in range(how_many):
user = create_fake_user(user_password)
@@ -973,13 +1011,19 @@ def create_orders(how_many=10):
yield f"Order: {order}"
-def create_product_promotions(how_many=5):
+def create_catalogue_promotions(how_many=5):
for _ in range(how_many):
- promotion = create_fake_promotion()
+ promotion = create_fake_catalogue_promotion()
update_products_discounted_prices_of_promotion_task.delay(promotion.pk)
yield f"Promotion: {promotion}"
+def create_order_promotions(how_many=5):
+ for _ in range(how_many):
+ promotion = create_fake_order_promotion()
+ yield f"Promotion: {promotion}"
+
+
def create_channel(channel_name, currency_code, slug=None, country=None):
if not slug:
slug = slugify(channel_name)
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index 0b269f78fa..a7b9b1dd55 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -18,6 +18,7 @@ class DiscountValueType:
class DiscountType:
SALE = "sale"
PROMOTION = "promotion"
+ ORDER_PROMOTION = "order_promotion"
VOUCHER = "voucher"
MANUAL = "manual"
CHOICES = [
@@ -25,6 +26,7 @@ class DiscountType:
(VOUCHER, "Voucher"),
(MANUAL, "Manual"),
(PROMOTION, "Promotion"),
+ (ORDER_PROMOTION, "Order promotion"),
]
@@ -40,6 +42,16 @@ class VoucherType:
]
+class PromotionType:
+ CATALOGUE = "catalogue"
+ ORDER = "order"
+
+ CHOICES = [
+ (CATALOGUE, "Catalogue"),
+ (ORDER, "Order"),
+ ]
+
+
class RewardValueType:
FIXED = "fixed"
PERCENTAGE = "percentage"
@@ -50,6 +62,14 @@ class RewardValueType:
]
+class RewardType:
+ SUBTOTAL_DISCOUNT = "subtotal_discount"
+
+ CHOICES = [
+ (SUBTOTAL_DISCOUNT, "subtotal_discount"),
+ ]
+
+
class PromotionEvents:
PROMOTION_CREATED = "promotion_created"
PROMOTION_UPDATED = "promotion_updated"
diff --git a/saleor/discount/error_codes.py b/saleor/discount/error_codes.py
index fee0087160..ce5d3b3431 100644
--- a/saleor/discount/error_codes.py
+++ b/saleor/discount/error_codes.py
@@ -20,6 +20,8 @@ class PromotionCreateErrorCode(Enum):
INVALID = "invalid"
MULTIPLE_CURRENCIES_NOT_ALLOWED = "multiple_currencies_not_allowed"
INVALID_PRECISION = "invalid_precision"
+ MISSING_CHANNELS = "missing_channels"
+ RULES_NUMBER_LIMIT = "rules_number_limit"
class PromotionUpdateErrorCode(Enum):
@@ -41,12 +43,15 @@ class PromotionRuleCreateErrorCode(Enum):
INVALID = "invalid"
MULTIPLE_CURRENCIES_NOT_ALLOWED = "multiple_currencies_not_allowed"
INVALID_PRECISION = "invalid_precision"
+ MISSING_CHANNELS = "missing_channels"
+ RULES_NUMBER_LIMIT = "rules_number_limit"
class PromotionRuleUpdateErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
INVALID = "invalid"
+ REQUIRED = "required"
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
MISSING_CHANNELS = "missing_channels"
MULTIPLE_CURRENCIES_NOT_ALLOWED = "multiple_currencies_not_allowed"
diff --git a/saleor/discount/interface.py b/saleor/discount/interface.py
index 7945f8ebde..1919f33269 100644
--- a/saleor/discount/interface.py
+++ b/saleor/discount/interface.py
@@ -44,7 +44,7 @@ def fetch_voucher_info(voucher: Voucher) -> VoucherInfo:
class VariantPromotionRuleInfo(NamedTuple):
rule: "PromotionRule"
- variant_listing_promotion_rule: "VariantChannelListingPromotionRule"
+ variant_listing_promotion_rule: Optional["VariantChannelListingPromotionRule"]
promotion: "Promotion"
promotion_translation: Optional["PromotionTranslation"]
rule_translation: Optional["PromotionRuleTranslation"]
@@ -62,22 +62,10 @@ def fetch_variant_rules_info(
rules_info = []
for listing_promotion_rule in listings_rules:
promotion = listing_promotion_rule.promotion_rule.promotion
- promotion_translations = [
- translation
- for translation in promotion.translations.all()
- if translation.language_code == translation_language_code
- ]
- promotion_translation = (
- promotion_translations[0] if promotion_translations else None
- )
-
- rule_translations = [
- translation
- for translation in listing_promotion_rule.promotion_rule.translations.all()
- if translation.language_code == translation_language_code
- ]
- rule_translation = rule_translations[0] if rule_translations else None
+ promotion_translation, rule_translation = get_rule_translations(
+ promotion, listing_promotion_rule.promotion_rule, translation_language_code
+ )
rules_info.append(
VariantPromotionRuleInfo(
rule=listing_promotion_rule.promotion_rule,
@@ -88,3 +76,25 @@ def fetch_variant_rules_info(
)
)
return rules_info
+
+
+def get_rule_translations(
+ promotion: "Promotion", rule: "PromotionRule", translation_language_code: str
+):
+ promotion_translations = [
+ translation
+ for translation in promotion.translations.all()
+ if translation.language_code == translation_language_code
+ ]
+ promotion_translation = (
+ promotion_translations[0] if promotion_translations else None
+ )
+
+ rule_translations = [
+ translation
+ for translation in rule.translations.all()
+ if translation.language_code == translation_language_code
+ ]
+ rule_translation = rule_translations[0] if rule_translations else None
+
+ return promotion_translation, rule_translation
diff --git a/saleor/discount/migrations/0074_auto_20240119_1029.py b/saleor/discount/migrations/0074_auto_20240119_1029.py
new file mode 100644
index 0000000000..28c0d2acfa
--- /dev/null
+++ b/saleor/discount/migrations/0074_auto_20240119_1029.py
@@ -0,0 +1,218 @@
+# Generated by Django 3.2.23 on 2024-01-19 14:02
+
+import uuid
+from decimal import Decimal
+
+import django.contrib.postgres.indexes
+import django.db.models.deletion
+from django.db import migrations, models
+
+import saleor.core.utils.json_serializer
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0063_checkout_base_total_and_subtotal"),
+ ("discount", "0073_auto_20231213_1535"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="promotion",
+ name="type",
+ field=models.CharField(
+ choices=[("catalogue", "Catalogue"), ("order", "Order")],
+ default="catalogue",
+ max_length=255,
+ ),
+ ),
+ migrations.AddField(
+ model_name="promotionrule",
+ name="order_predicate",
+ field=models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ ),
+ ),
+ migrations.AddField(
+ model_name="promotionrule",
+ name="reward_type",
+ field=models.CharField(
+ blank=True,
+ choices=[("subtotal_discount", "subtotal_discount")],
+ max_length=255,
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="checkoutlinediscount",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("sale", "Sale"),
+ ("voucher", "Voucher"),
+ ("manual", "Manual"),
+ ("promotion", "Promotion"),
+ ("order_promotion", "Order promotion"),
+ ],
+ default="manual",
+ max_length=64,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orderdiscount",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("sale", "Sale"),
+ ("voucher", "Voucher"),
+ ("manual", "Manual"),
+ ("promotion", "Promotion"),
+ ("order_promotion", "Order promotion"),
+ ],
+ default="manual",
+ max_length=64,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orderlinediscount",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("sale", "Sale"),
+ ("voucher", "Voucher"),
+ ("manual", "Manual"),
+ ("promotion", "Promotion"),
+ ("order_promotion", "Order promotion"),
+ ],
+ default="manual",
+ max_length=64,
+ ),
+ ),
+ migrations.CreateModel(
+ name="CheckoutDiscount",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ unique=True,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
+ (
+ "type",
+ models.CharField(
+ choices=[
+ ("sale", "Sale"),
+ ("voucher", "Voucher"),
+ ("manual", "Manual"),
+ ("promotion", "Promotion"),
+ ("order_promotion", "Order promotion"),
+ ],
+ default="manual",
+ max_length=64,
+ ),
+ ),
+ (
+ "value_type",
+ models.CharField(
+ choices=[("fixed", "fixed"), ("percentage", "%")],
+ default="fixed",
+ max_length=10,
+ ),
+ ),
+ (
+ "value",
+ models.DecimalField(
+ decimal_places=3, default=Decimal("0.0"), max_digits=12
+ ),
+ ),
+ (
+ "amount_value",
+ models.DecimalField(
+ decimal_places=3, default=Decimal("0.0"), max_digits=12
+ ),
+ ),
+ ("currency", models.CharField(max_length=3)),
+ ("name", models.CharField(blank=True, max_length=255, null=True)),
+ (
+ "translated_name",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ("reason", models.TextField(blank=True, null=True)),
+ (
+ "voucher_code",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ (
+ "checkout",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="discounts",
+ to="checkout.checkout",
+ ),
+ ),
+ (
+ "promotion_rule",
+ models.ForeignKey(
+ blank=True,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="discount.promotionrule",
+ ),
+ ),
+ (
+ "voucher",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="discount.voucher",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("created_at", "id"),
+ },
+ ),
+ migrations.AddIndex(
+ model_name="checkoutdiscount",
+ index=django.contrib.postgres.indexes.BTreeIndex(
+ fields=["promotion_rule"], name="checkoutdiscount_rule_idx"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="checkoutdiscount",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["name", "translated_name"], name="discount_ch_name_64e096_gin"
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="checkoutdiscount",
+ index=django.contrib.postgres.indexes.GinIndex(
+ fields=["voucher_code"], name="checkoutdiscount_voucher_idx"
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="checkoutdiscount",
+ unique_together={("checkout_id", "promotion_rule_id")},
+ ),
+ migrations.RunSQL(
+ "ALTER TABLE discount_promotionrule ALTER COLUMN order_predicate SET DEFAULT '{}';",
+ migrations.RunSQL.noop,
+ ),
+ migrations.RunSQL(
+ "ALTER TABLE discount_promotion ALTER COLUMN type SET DEFAULT 'catalogue';",
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 9b6f423d9c..d2712bb87b 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -27,6 +27,8 @@ from . import (
DiscountType,
DiscountValueType,
PromotionEvents,
+ PromotionType,
+ RewardType,
RewardValueType,
VoucherType,
)
@@ -310,6 +312,11 @@ PromotionManager = models.Manager.from_queryset(PromotionQueryset)
class Promotion(ModelWithMetadata):
id = models.UUIDField(primary_key=True, editable=False, unique=True, default=uuid4)
name = models.CharField(max_length=255)
+ type = models.CharField(
+ max_length=255,
+ choices=PromotionType.CHOICES,
+ default=PromotionType.CATALOGUE,
+ )
description = SanitizedJSONField(blank=True, null=True, sanitizer=clean_editor_js)
old_sale_id = models.IntegerField(blank=True, null=True, unique=True)
start_date = models.DateTimeField(default=timezone.now)
@@ -373,6 +380,9 @@ class PromotionRule(models.Model):
catalogue_predicate = models.JSONField(
blank=True, default=dict, encoder=CustomJsonEncoder
)
+ order_predicate = models.JSONField(
+ blank=True, default=dict, encoder=CustomJsonEncoder
+ )
variants = models.ManyToManyField("product.ProductVariant", blank=True)
reward_value_type = models.CharField(
max_length=255, choices=RewardValueType.CHOICES, blank=True, null=True
@@ -383,6 +393,9 @@ class PromotionRule(models.Model):
null=True,
blank=True,
)
+ reward_type = models.CharField(
+ max_length=255, choices=RewardType.CHOICES, blank=True, null=True
+ )
old_channel_listing_id = models.IntegerField(blank=True, null=True, unique=True)
class Meta:
@@ -433,7 +446,7 @@ class BaseDiscount(models.Model):
id = models.UUIDField(primary_key=True, editable=False, unique=True, default=uuid4)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
type = models.CharField(
- max_length=10,
+ max_length=64,
choices=DiscountType.CHOICES,
default=DiscountType.MANUAL,
)
@@ -519,6 +532,26 @@ class OrderLineDiscount(BaseDiscount):
ordering = ("created_at", "id")
+class CheckoutDiscount(BaseDiscount):
+ checkout = models.ForeignKey(
+ "checkout.Checkout",
+ related_name="discounts",
+ blank=True,
+ null=True,
+ on_delete=models.CASCADE,
+ )
+
+ class Meta:
+ indexes = [
+ BTreeIndex(fields=["promotion_rule"], name="checkoutdiscount_rule_idx"),
+ # Orders searching index
+ GinIndex(fields=["name", "translated_name"]),
+ GinIndex(fields=["voucher_code"], name="checkoutdiscount_voucher_idx"),
+ ]
+ ordering = ("created_at", "id")
+ unique_together = ("checkout_id", "promotion_rule_id")
+
+
class CheckoutLineDiscount(BaseDiscount):
line = models.ForeignKey(
"checkout.CheckoutLine",
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
index 84542395c8..6f62184fd6 100644
--- a/saleor/discount/tasks.py
+++ b/saleor/discount/tasks.py
@@ -9,7 +9,7 @@ from django.conf import settings
from django.db.models import Exists, F, OuterRef, Q, QuerySet
from ..celeryconf import app
-from ..graphql.discount.utils import get_variants_for_predicate
+from ..graphql.discount.utils import get_variants_for_catalogue_predicate
from ..order import OrderStatus
from ..order.models import Order, OrderLine
from ..plugins.manager import get_plugins_manager
@@ -184,7 +184,7 @@ def fetch_promotion_variants_and_product_ids(promotions: "QuerySet[Promotion]"):
Exists(promotions.filter(id=OuterRef("promotion_id")))
)
for rule in rules:
- rule_variants = get_variants_for_predicate(rule.catalogue_predicate)
+ rule_variants = get_variants_for_catalogue_predicate(rule.catalogue_predicate)
variants |= rule_variants
promotion_id_to_variants[rule.promotion_id] |= rule_variants
products = Product.objects.filter(
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index 09974ec90f..e074d138af 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -98,11 +98,11 @@ def test_valid_voucher_min_checkout_items_quantity(voucher):
@pytest.mark.integration
@pytest.mark.django_db(transaction=True)
-def test_percentage_discounts(product, channel_USD, promotion_without_rules):
+def test_percentage_discounts(product, channel_USD, catalogue_promotion_without_rules):
# given
variant = product.variants.get()
reward_value = Decimal("50")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [graphene.Node.to_global_id("Product", variant.product.id)]
@@ -131,11 +131,11 @@ def test_percentage_discounts(product, channel_USD, promotion_without_rules):
@pytest.mark.integration
@pytest.mark.django_db(transaction=True)
-def test_fixed_discounts(product, channel_USD, promotion_without_rules):
+def test_fixed_discounts(product, channel_USD, catalogue_promotion_without_rules):
# given
variant = product.variants.get()
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [graphene.Node.to_global_id("Product", variant.product.id)]
@@ -471,8 +471,9 @@ def test_validate_voucher_not_applicable_once_per_customer(
date_time_now = timezone.now()
-def test_get_discount_name_only_rule_name(promotion):
+def test_get_discount_name_only_rule_name(catalogue_promotion):
# given
+ promotion = catalogue_promotion
promotion.name = ""
promotion.save(update_fields=["name"])
@@ -485,8 +486,9 @@ def test_get_discount_name_only_rule_name(promotion):
assert name == rule.name
-def test_get_discount_name_only_rule_promotion_name(promotion):
+def test_get_discount_name_only_rule_promotion_name(catalogue_promotion):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.first()
rule.name = ""
rule.save(update_fields=["name"])
@@ -498,8 +500,9 @@ def test_get_discount_name_only_rule_promotion_name(promotion):
assert name == promotion.name
-def test_get_discount_name_rule_and_promotion_name(promotion):
+def test_get_discount_name_rule_and_promotion_name(catalogue_promotion):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.first()
# when
@@ -509,8 +512,9 @@ def test_get_discount_name_rule_and_promotion_name(promotion):
assert name == f"{promotion.name}: {rule.name}"
-def test_get_discount_name_empty_names(promotion):
+def test_get_discount_name_empty_names(catalogue_promotion):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.first()
rule.name = ""
diff --git a/saleor/discount/tests/test_rounding_issue.py b/saleor/discount/tests/test_rounding_issue.py
index 78a32b4cc5..247cbd3d2b 100644
--- a/saleor/discount/tests/test_rounding_issue.py
+++ b/saleor/discount/tests/test_rounding_issue.py
@@ -113,6 +113,7 @@ def test_rounding_issue_with_percentage_promotion(
# when
create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info,
lines_info,
)
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 d227c7020f..b92cb1d5c6 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
@@ -1,22 +1,33 @@
from decimal import Decimal
+from unittest.mock import patch
+import before_after
import graphene
import pytest
from django.utils import timezone
from freezegun import freeze_time
+from prices import Money, TaxedMoney
+from ....checkout.base_calculations import base_checkout_total
from ....discount.interface import VariantPromotionRuleInfo
from ....product.models import VariantChannelListingPromotionRule
-from ... import DiscountType, RewardValueType
-from ...models import CheckoutLineDiscount, PromotionRule
-from ...utils import create_or_update_discount_objects_from_promotion_for_checkout
+from ... import DiscountType, RewardType, RewardValueType
+from ...models import CheckoutDiscount, CheckoutLineDiscount, PromotionRule
+from ...utils import (
+ _create_or_update_checkout_discount,
+ create_discount_objects_for_order_promotions,
+ create_or_update_discount_objects_from_promotion_for_checkout,
+)
def test_create_or_update_discount_objects_from_promotion_for_checkout_no_discount(
+ checkout_info,
checkout_lines_info,
):
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
for checkout_line_info in checkout_lines_info:
@@ -25,14 +36,17 @@ def test_create_or_update_discount_objects_from_promotion_for_checkout_no_discou
@freeze_time("2020-12-12 12:00:00")
def test_create_fixed_discount(
- checkout_lines_info, promotion_without_rules, promotion_translation_fr
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+ promotion_translation_fr,
):
# given
line_info1 = checkout_lines_info[0]
product_line1 = line_info1.product
reward_value = Decimal("2")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -59,14 +73,16 @@ def test_create_fixed_discount(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=promotion_translation_fr,
rule_translation=None,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -89,7 +105,7 @@ def test_create_fixed_discount(
assert (
discount_from_info.name
== discount_from_db.name
- == f"{promotion_without_rules.name}: {rule.name}"
+ == f"{catalogue_promotion_without_rules.name}: {rule.name}"
)
assert discount_from_info.reason == discount_from_db.reason is None
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
@@ -106,14 +122,16 @@ def test_create_fixed_discount(
@freeze_time("2020-12-12 12:00:00")
def test_create_fixed_discount_multiple_quantity_in_lines(
- checkout_lines_with_multiple_quantity_info, promotion_without_rules
+ checkout_info,
+ checkout_lines_with_multiple_quantity_info,
+ catalogue_promotion_without_rules,
):
# given
line_info1 = checkout_lines_with_multiple_quantity_info[0]
product_line1 = line_info1.product
reward_value = Decimal("2")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [graphene.Node.to_global_id("Product", product_line1.id)]
@@ -141,7 +159,7 @@ def test_create_fixed_discount_multiple_quantity_in_lines(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
@@ -149,7 +167,7 @@ def test_create_fixed_discount_multiple_quantity_in_lines(
# when
create_or_update_discount_objects_from_promotion_for_checkout(
- checkout_lines_with_multiple_quantity_info
+ checkout_info, checkout_lines_with_multiple_quantity_info
)
# then
@@ -173,7 +191,9 @@ def test_create_fixed_discount_multiple_quantity_in_lines(
)
assert discount_from_info.currency == discount_from_db.currency == "USD"
assert (
- discount_from_info.name == discount_from_db.name == promotion_without_rules.name
+ discount_from_info.name
+ == discount_from_db.name
+ == catalogue_promotion_without_rules.name
)
assert discount_from_info.reason == discount_from_db.reason is None
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
@@ -184,14 +204,16 @@ def test_create_fixed_discount_multiple_quantity_in_lines(
def test_create_fixed_discount_multiple_quantity_in_lines_discount_bigger_than_total(
- checkout_lines_with_multiple_quantity_info, promotion_without_rules
+ checkout_info,
+ checkout_lines_with_multiple_quantity_info,
+ catalogue_promotion_without_rules,
):
# given
line_info1 = checkout_lines_with_multiple_quantity_info[0]
product_line1 = line_info1.product
reward_value = Decimal(15)
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -219,7 +241,7 @@ def test_create_fixed_discount_multiple_quantity_in_lines_discount_bigger_than_t
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
@@ -229,7 +251,7 @@ def test_create_fixed_discount_multiple_quantity_in_lines_discount_bigger_than_t
# when
create_or_update_discount_objects_from_promotion_for_checkout(
- checkout_lines_with_multiple_quantity_info
+ checkout_info, checkout_lines_with_multiple_quantity_info
)
# then
@@ -255,13 +277,15 @@ def test_create_fixed_discount_multiple_quantity_in_lines_discount_bigger_than_t
@freeze_time("2020-12-12 12:00:00")
-def test_create_percentage_discount(checkout_lines_info, promotion_without_rules):
+def test_create_percentage_discount(
+ checkout_info, checkout_lines_info, catalogue_promotion_without_rules
+):
# given
line_info1 = checkout_lines_info[0]
product_line1 = line_info1.product
reward_value = Decimal("10")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -290,14 +314,16 @@ def test_create_percentage_discount(checkout_lines_info, promotion_without_rules
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -322,7 +348,7 @@ def test_create_percentage_discount(checkout_lines_info, promotion_without_rules
assert (
discount_from_info.name
== discount_from_db.name
- == f"{promotion_without_rules.name}: {rule.name}"
+ == f"{catalogue_promotion_without_rules.name}: {rule.name}"
)
assert discount_from_info.reason == discount_from_db.reason is None
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
@@ -334,14 +360,16 @@ def test_create_percentage_discount(checkout_lines_info, promotion_without_rules
@freeze_time("2020-12-12 12:00:00")
def test_create_percentage_discount_multiple_quantity_in_lines(
- checkout_lines_with_multiple_quantity_info, promotion_without_rules
+ checkout_info,
+ checkout_lines_with_multiple_quantity_info,
+ catalogue_promotion_without_rules,
):
# given
line_info1 = checkout_lines_with_multiple_quantity_info[0]
product_line1 = line_info1.product
reward_value = Decimal("10")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -370,7 +398,7 @@ def test_create_percentage_discount_multiple_quantity_in_lines(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
@@ -380,7 +408,7 @@ def test_create_percentage_discount_multiple_quantity_in_lines(
# when
create_or_update_discount_objects_from_promotion_for_checkout(
- checkout_lines_with_multiple_quantity_info
+ checkout_info, checkout_lines_with_multiple_quantity_info
)
# then
@@ -403,7 +431,7 @@ def test_create_percentage_discount_multiple_quantity_in_lines(
== expected_discount_amount
)
assert discount_from_info.currency == discount_from_db.currency == "USD"
- discount_name = f"{promotion_without_rules.name}: {rule.name}"
+ discount_name = f"{catalogue_promotion_without_rules.name}: {rule.name}"
assert discount_from_info.name == discount_from_db.name == discount_name
assert discount_from_info.reason == discount_from_db.reason is None
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
@@ -414,7 +442,7 @@ def test_create_percentage_discount_multiple_quantity_in_lines(
def test_create_discount_multiple_rules_applied(
- checkout_lines_info, promotion_without_rules
+ checkout_info, checkout_lines_info, catalogue_promotion_without_rules
):
# given
line_info1 = checkout_lines_info[0]
@@ -426,7 +454,7 @@ def test_create_discount_multiple_rules_applied(
[
PromotionRule(
name="Percentage promotion rule 1",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.FIXED,
reward_value=reward_value_1,
catalogue_predicate={
@@ -437,7 +465,7 @@ def test_create_discount_multiple_rules_applied(
),
PromotionRule(
name="Percentage promotion rule 2",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.PERCENTAGE,
reward_value=reward_value_2,
catalogue_predicate={
@@ -486,21 +514,23 @@ def test_create_discount_multiple_rules_applied(
VariantPromotionRuleInfo(
rule=rule_1,
variant_listing_promotion_rule=listing_promotion_rule_1,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
),
VariantPromotionRuleInfo(
rule=rule_2,
variant_listing_promotion_rule=listing_promotion_rule_2,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
),
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 2
@@ -533,7 +563,7 @@ def test_create_discount_multiple_rules_applied(
def test_two_promotions_applied_to_two_different_lines(
- checkout_lines_info, promotion_without_rules
+ checkout_info, checkout_lines_info, catalogue_promotion_without_rules
):
# given
line_info1 = checkout_lines_info[0]
@@ -548,7 +578,7 @@ def test_two_promotions_applied_to_two_different_lines(
[
PromotionRule(
name="Percentage promotion rule 1",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.FIXED,
reward_value=reward_value_1,
catalogue_predicate={
@@ -559,7 +589,7 @@ def test_two_promotions_applied_to_two_different_lines(
),
PromotionRule(
name="Percentage promotion rule 2",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.FIXED,
reward_value=reward_value_2,
catalogue_predicate={
@@ -608,7 +638,7 @@ def test_two_promotions_applied_to_two_different_lines(
VariantPromotionRuleInfo(
rule=rule_1,
variant_listing_promotion_rule=listing_promotion_rule_1,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
@@ -617,14 +647,16 @@ def test_two_promotions_applied_to_two_different_lines(
VariantPromotionRuleInfo(
rule=rule_2,
variant_listing_promotion_rule=listing_promotion_rule_2,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -649,7 +681,7 @@ def test_two_promotions_applied_to_two_different_lines(
assert (
discount_from_info_1.name
== discount_from_db_1.name
- == f"{promotion_without_rules.name}: {rule_1.name}"
+ == f"{catalogue_promotion_without_rules.name}: {rule_1.name}"
)
assert discount_from_info_1.reason == discount_from_db_1.reason is None
assert (
@@ -680,7 +712,7 @@ def test_two_promotions_applied_to_two_different_lines(
assert (
discount_from_info_2.name
== discount_from_db_2.name
- == f"{promotion_without_rules.name}: {rule_2.name}"
+ == f"{catalogue_promotion_without_rules.name}: {rule_2.name}"
)
assert discount_from_info_2.reason == discount_from_db_2.reason is None
assert (
@@ -692,7 +724,7 @@ def test_two_promotions_applied_to_two_different_lines(
@freeze_time("2020-12-12 12:00:00")
def test_create_percentage_discount_1_cent_variant_on_10_percentage_discount(
- checkout_lines_info, promotion_without_rules
+ checkout_info, checkout_lines_info, catalogue_promotion_without_rules
):
# given
line_info1 = checkout_lines_info[0]
@@ -703,7 +735,7 @@ def test_create_percentage_discount_1_cent_variant_on_10_percentage_discount(
product_line1 = line_info1.product
reward_value = Decimal("10")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -739,14 +771,16 @@ def test_create_percentage_discount_1_cent_variant_on_10_percentage_discount(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -771,7 +805,7 @@ def test_create_percentage_discount_1_cent_variant_on_10_percentage_discount(
assert (
discount_from_info.name
== discount_from_db.name
- == f"{promotion_without_rules.name}: {rule.name}"
+ == f"{catalogue_promotion_without_rules.name}: {rule.name}"
)
assert discount_from_info.reason == discount_from_db.reason is None
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
@@ -781,13 +815,15 @@ def test_create_percentage_discount_1_cent_variant_on_10_percentage_discount(
assert not checkout_line_info.discounts
-def test_promotion_not_valid_anymore(checkout_lines_info, promotion_without_rules):
+def test_promotion_not_valid_anymore(
+ checkout_info, checkout_lines_info, catalogue_promotion_without_rules
+):
# given
line_info1 = checkout_lines_info[0]
product_line1 = line_info1.product
reward_value = Decimal("2")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -815,7 +851,9 @@ def test_promotion_not_valid_anymore(checkout_lines_info, promotion_without_rule
line_info1.discounts = [line_discount]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 0
@@ -824,7 +862,7 @@ def test_promotion_not_valid_anymore(checkout_lines_info, promotion_without_rule
def test_one_of_promotion_rule_not_valid_anymore_one_updated(
- checkout_lines_info, promotion_without_rules
+ checkout_info, checkout_lines_info, catalogue_promotion_without_rules
):
# given
line_info1 = checkout_lines_info[0]
@@ -836,7 +874,7 @@ def test_one_of_promotion_rule_not_valid_anymore_one_updated(
[
PromotionRule(
name="Percentage promotion rule 1",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.FIXED,
reward_value=reward_value_1,
catalogue_predicate={
@@ -847,7 +885,7 @@ def test_one_of_promotion_rule_not_valid_anymore_one_updated(
),
PromotionRule(
name="Percentage promotion rule 2",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.PERCENTAGE,
reward_value=reward_value_2,
catalogue_predicate={
@@ -904,14 +942,16 @@ def test_one_of_promotion_rule_not_valid_anymore_one_updated(
VariantPromotionRuleInfo(
rule=rule_1,
variant_listing_promotion_rule=listing_promotion_rule_1,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -932,7 +972,7 @@ def test_one_of_promotion_rule_not_valid_anymore_one_updated(
assert (
discount_from_info.name
== line_discount_1.name
- == f"{promotion_without_rules.name}: {rule_1.name}"
+ == f"{catalogue_promotion_without_rules.name}: {rule_1.name}"
)
assert (
discount_from_info.amount_value
@@ -945,14 +985,17 @@ def test_one_of_promotion_rule_not_valid_anymore_one_updated(
def test_create_discount_with_promotion_translation(
- checkout_lines_info, promotion_without_rules, promotion_translation_fr
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+ promotion_translation_fr,
):
# given
line_info1 = checkout_lines_info[0]
product_line1 = line_info1.product
reward_value = Decimal("2")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -979,14 +1022,16 @@ def test_create_discount_with_promotion_translation(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=promotion_translation_fr,
rule_translation=None,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -1004,14 +1049,17 @@ def test_create_discount_with_promotion_translation(
def test_create_discount_with_rule_translation(
- checkout_lines_info, promotion_without_rules, promotion_rule_translation_fr
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+ promotion_rule_translation_fr,
):
# given
line_info1 = checkout_lines_info[0]
product_line1 = line_info1.product
reward_value = Decimal("2")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -1038,14 +1086,16 @@ def test_create_discount_with_rule_translation(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=promotion_rule_translation_fr,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -1063,8 +1113,9 @@ def test_create_discount_with_rule_translation(
def test_create_discount_with_promotion_and_rule_translation(
+ checkout_info,
checkout_lines_info,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
promotion_translation_fr,
promotion_rule_translation_fr,
):
@@ -1073,7 +1124,7 @@ def test_create_discount_with_promotion_and_rule_translation(
product_line1 = line_info1.product
reward_value = Decimal("2")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -1100,14 +1151,16 @@ def test_create_discount_with_promotion_and_rule_translation(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=promotion_translation_fr,
rule_translation=promotion_rule_translation_fr,
)
]
# when
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines_info)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
# then
assert len(line_info1.discounts) == 1
@@ -1122,3 +1175,578 @@ def test_create_discount_with_promotion_and_rule_translation(
for checkout_line_info in checkout_lines_info[1:]:
assert not checkout_line_info.discounts
+
+
+def test_create_or_update_discount_objects_from_promotion_for_checkout_voucher_set(
+ checkout_info, checkout_lines_info, order_promotion_rule, voucher
+):
+ # given
+ checkout_info.voucher = voucher
+ checkout_info.checkout.voucher_code = voucher.code
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert not checkout_info.discounts
+ assert not checkout_info.checkout.discounts.all()
+
+
+@patch("saleor.discount.utils.base_checkout_delivery_price")
+@patch("saleor.discount.utils.base_checkout_subtotal")
+def test_create_or_update_discount_objects_from_promotion_no_applicable_rules(
+ base_checkout_subtotal_mock,
+ base_checkout_delivery_price_mock,
+ checkout_info,
+ checkout_lines_info,
+ order_promotion_rule,
+ voucher,
+):
+ # given
+ checkout = checkout_info.checkout
+ currency = checkout.currency
+ price = Money("10", currency)
+ base_checkout_subtotal_mock.return_value = price
+ base_checkout_delivery_price_mock.return_value = Money("0", currency)
+ checkout.total = TaxedMoney(net=price, gross=price)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert not checkout_info.discounts
+ assert not checkout_info.checkout.discounts.all()
+
+
+def test_create_or_update_discount_objects_from_promotion(
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+ price = Money("30", checkout_info.checkout.currency)
+ checkout.total = TaxedMoney(net=price, gross=price)
+ checkout.subtotal = TaxedMoney(net=price, gross=price)
+ checkout.save(
+ update_fields=[
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ ]
+ )
+
+ rules = PromotionRule.objects.bulk_create(
+ [
+ PromotionRule(
+ name="Order promotion rule 1",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 10,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("25"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ ),
+ PromotionRule(
+ name="Order promotion rule 2",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("50"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ ),
+ ]
+ )
+ for rule in rules:
+ rule.channels.add(checkout_info.channel)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert checkout_info.checkout.discounts.count() == 1
+ assert len(checkout_info.discounts) == 1
+ assert checkout_info.discounts[0].promotion_rule == rules[1]
+
+
+@patch("saleor.discount.utils.base_checkout_delivery_price")
+@patch("saleor.discount.utils.base_checkout_subtotal")
+def test_create_or_update_discount_objects_from_promotion_best_rule_applies(
+ subtotal_mock,
+ delivery_price_mock,
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+
+ delivery_price = Money("10", checkout_info.checkout.currency)
+ price = Money("30", checkout_info.checkout.currency)
+ checkout.total = TaxedMoney(net=price, gross=price)
+ checkout.subtotal = TaxedMoney(net=price, gross=price)
+ checkout.save(
+ update_fields=[
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ ]
+ )
+
+ subtotal_mock.return_value = price
+ delivery_price_mock.return_value = delivery_price
+
+ rules = PromotionRule.objects.bulk_create(
+ [
+ PromotionRule(
+ name="Order promotion rule 1",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 10,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal("12"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ ),
+ PromotionRule(
+ name="Order promotion rule 2",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("25"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ ),
+ PromotionRule(
+ name="Order promotion rule 1",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 100,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("50"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ ),
+ ]
+ )
+ for rule in rules:
+ rule.channels.add(checkout_info.channel)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert checkout_info.checkout.discounts.count() == 1
+ assert len(checkout_info.discounts) == 1
+ assert checkout_info.discounts[0].promotion_rule == rules[0]
+ discount = checkout_info.discounts[0]
+ assert discount.promotion_rule == rules[0]
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.value_type == RewardValueType.FIXED
+ assert discount.value == rules[0].reward_value
+ assert discount.amount_value == rules[0].reward_value
+ assert discount.name == f"{promotion.name}: {rules[0].name}"
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+
+@patch("saleor.discount.utils.base_checkout_delivery_price")
+@patch("saleor.discount.utils.base_checkout_subtotal")
+def test_create_or_update_discount_objects_from_promotion_subtotal_price_discount(
+ subtotal_mock,
+ delivery_price_mock,
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+
+ delivery_price = Money("10", checkout_info.checkout.currency)
+ price = Money("30", checkout_info.checkout.currency)
+ checkout.base_subtotal = price
+ checkout.base_total = price + delivery_price
+ checkout.save(
+ update_fields=[
+ "base_total_amount",
+ "base_subtotal_amount",
+ ]
+ )
+
+ subtotal_mock.return_value = price
+ delivery_price_mock.return_value = delivery_price
+
+ rules = PromotionRule.objects.bulk_create(
+ [
+ PromotionRule(
+ name="Order promotion rule 2",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("50"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ ),
+ ]
+ )
+ for rule in rules:
+ rule.channels.add(checkout_info.channel)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert checkout_info.checkout.discounts.count() == 1
+ assert len(checkout_info.discounts) == 1
+ assert checkout_info.discounts[0].promotion_rule == rules[0]
+ discount = checkout_info.discounts[0]
+ assert discount.amount_value == checkout.base_subtotal.amount * Decimal("0.5")
+
+
+def test_create_or_update_discount_from_promotion_voucher_code_set_checkout_discount(
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+ voucher,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+ checkout_info.voucher = voucher
+ checkout_info.checkout.voucher_code = voucher.code
+
+ price = Money("30", checkout_info.checkout.currency)
+ checkout.total = TaxedMoney(net=price, gross=price)
+ checkout.subtotal = TaxedMoney(net=price, gross=price)
+ checkout.save(
+ update_fields=[
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ ]
+ )
+
+ rule = PromotionRule.objects.create(
+ name="Order promotion rule 1",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 10,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("25"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(checkout_info.channel)
+ discount = CheckoutDiscount.objects.create(
+ checkout=checkout,
+ promotion_rule=rule,
+ type=DiscountType.ORDER_PROMOTION,
+ )
+ checkout_info.discounts = [discount]
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert checkout_info.discounts == []
+ assert not checkout.discounts.all()
+ with pytest.raises(CheckoutDiscount.DoesNotExist):
+ discount.refresh_from_db()
+
+
+def test_create_or_update_discount_from_promotion_checkout_discount_updated(
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+ promotion_rule,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+
+ checkout_total = base_checkout_total(checkout_info, checkout_lines_info)
+ checkout.total = TaxedMoney(net=checkout_total, gross=checkout_total)
+ checkout.subtotal = TaxedMoney(net=checkout_total, gross=checkout_total)
+ checkout.save(
+ update_fields=[
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ ]
+ )
+
+ rule = PromotionRule.objects.create(
+ name="Order promotion rule 1",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 10,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("25"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(checkout_info.channel)
+ discount = CheckoutDiscount.objects.create(
+ checkout=checkout,
+ promotion_rule=promotion_rule,
+ type=DiscountType.ORDER_PROMOTION,
+ )
+ checkout_info.discounts = [discount]
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert checkout_info.discounts == [discount]
+ assert checkout.discounts.count() == 1
+ discount = checkout_info.discounts[0]
+ assert discount.promotion_rule_id == rule.id
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.value_type == rule.reward_value_type
+ assert discount.value == rule.reward_value
+ assert discount.amount_value == (checkout_total * rule.reward_value / 100).amount
+ assert discount.name == f"{promotion.name}: {rule.name}"
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+
+def test_create_or_update_discount_from_promotion_rule_not_applies_anymore(
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+ promotion_rule,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+
+ checkout_total = base_checkout_total(checkout_info, checkout_lines_info)
+ checkout.total = TaxedMoney(net=checkout_total, gross=checkout_total)
+ checkout.subtotal = TaxedMoney(net=checkout_total, gross=checkout_total)
+ checkout.save(
+ update_fields=[
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ ]
+ )
+
+ rule = PromotionRule.objects.create(
+ name="Order promotion rule 1",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 200,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("25"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(checkout_info.channel)
+ discount = CheckoutDiscount.objects.create(
+ checkout=checkout,
+ promotion_rule=promotion_rule,
+ type=DiscountType.ORDER_PROMOTION,
+ )
+ checkout_info.discounts = [discount]
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert checkout_info.discounts == []
+ assert not checkout.discounts.all()
+ with pytest.raises(CheckoutDiscount.DoesNotExist):
+ discount.refresh_from_db()
+
+
+def test_create_discount_objects_for_order_promotions_race_condition(
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+ channel = checkout_info.channel
+
+ reward_value = Decimal("2")
+ rule = promotion.rules.create(
+ order_predicate={
+ "total_price": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel)
+
+ rule0 = promotion.rules.create(
+ order_predicate={
+ "total_price": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal("1"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule0.channels.add(channel)
+
+ # when
+ def call_before_creating_discount_object(*args, **kwargs):
+ CheckoutDiscount.objects.create(
+ checkout=checkout,
+ promotion_rule=rule0,
+ type=DiscountType.ORDER_PROMOTION,
+ value_type=rule0.reward_value_type,
+ value=rule0.reward_value,
+ amount_value=rule0.reward_value,
+ currency=channel.currency_code,
+ )
+
+ with before_after.before(
+ "saleor.discount.utils._create_or_update_checkout_discount",
+ call_before_creating_discount_object,
+ ):
+ create_discount_objects_for_order_promotions(checkout_info, checkout_lines_info)
+
+ # then
+ discounts = list(checkout_info.checkout.discounts.all())
+ assert len(discounts) == 1
+ assert discounts[0].amount_value == reward_value
+
+
+def test_create_or_update_checkout_discount_race_condition(
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+ checkout = checkout_info.checkout
+ channel = checkout_info.channel
+ currency = channel.currency_code
+
+ reward_value = Decimal("2")
+ rule = promotion.rules.create(
+ order_predicate={
+ "total_price": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel)
+
+ def call_update(*args, **kwargs):
+ _create_or_update_checkout_discount(
+ checkout,
+ checkout_info,
+ rule,
+ Money(reward_value, currency),
+ currency,
+ promotion,
+ True,
+ )
+
+ with before_after.before(
+ "saleor.discount.utils.get_rule_translations", call_update
+ ):
+ call_update()
+
+ # then
+ discounts = list(checkout_info.checkout.discounts.all())
+ assert len(discounts) == 1
diff --git a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py
new file mode 100644
index 0000000000..a090088b4c
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py
@@ -0,0 +1,84 @@
+from decimal import Decimal
+
+from ... import RewardType, RewardValueType
+from ...models import PromotionRule
+from ...utils import fetch_promotion_rules_for_checkout
+
+
+def test_fetch_promotion_rules_for_checkout(
+ checkout, checkout_for_cc, order_promotion_rule
+):
+ # given
+ rule = order_promotion_rule
+
+ checkout.base_total_amount = 100
+ checkout.base_subtotal_amount = 100
+ checkout.total_gross_amount = 100
+ checkout.save(
+ update_fields=[
+ "total_gross_amount",
+ "base_total_amount",
+ "base_subtotal_amount",
+ ]
+ )
+
+ # when
+ rules_per_promotion_id = fetch_promotion_rules_for_checkout(checkout)
+
+ # then
+ assert len(rules_per_promotion_id) == 1
+ assert rules_per_promotion_id == [rule]
+
+
+def test_fetch_promotion_rules_for_checkout_no_matching_rule(
+ checkout,
+ checkout_JPY,
+ order_promotion_rule,
+):
+ # given
+ checkout.base_total_amount = 10
+ checkout.base_subtotal_amount = 10
+ checkout.total_gross_amount = 10
+ checkout.save(
+ update_fields=[
+ "total_gross_amount",
+ "base_total_amount",
+ "base_subtotal_amount",
+ ]
+ )
+
+ # when
+ rules_per_promotion_id = fetch_promotion_rules_for_checkout(checkout)
+
+ # then
+ assert not rules_per_promotion_id
+
+
+def test_fetch_promotion_rules_for_checkout_relevant_channel_only(
+ checkout_JPY, order_promotion_rule
+):
+ # given
+ promotion = order_promotion_rule.promotion
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 0}}}
+ }
+ rule_1 = order_promotion_rule
+ rule_1.order_predicate = order_predicate
+ rule_1.save(update_fields=["order_predicate"])
+
+ rule_2 = PromotionRule.objects.create(
+ name="Another promotion rule",
+ promotion=promotion,
+ order_predicate=order_predicate,
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("10"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule_2.channels.add(checkout_JPY.channel)
+
+ # when
+ rules_per_promotion_id = fetch_promotion_rules_for_checkout(checkout_JPY)
+
+ # then
+ assert len(rules_per_promotion_id) == 1
+ assert rules_per_promotion_id == [rule_2]
diff --git a/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py b/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py
index cae4c0b7e9..1a2394374d 100644
--- a/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py
+++ b/saleor/discount/tests/test_utils/test_get_variants_to_promotions_map.py
@@ -10,10 +10,10 @@ from ...utils import get_variants_to_promotion_rules_map
def test_get_variants_to_promotions_map(
- promotion_without_rules, product, product_with_two_variants, channel_USD
+ catalogue_promotion_without_rules, product, product_with_two_variants, channel_USD
):
# given
- promotion = promotion_without_rules
+ promotion = catalogue_promotion_without_rules
variant = product.variants.first()
percentage_reward_value = Decimal("10")
@@ -63,10 +63,10 @@ def test_get_variants_to_promotions_map(
def test_get_variants_to_promotions_map_from_different_promotions(
- promotion_without_rules, product, channel_USD
+ catalogue_promotion_without_rules, product, channel_USD
):
# given
- promotion = promotion_without_rules
+ promotion = catalogue_promotion_without_rules
promotion_2 = Promotion.objects.create(
name="Promotion",
)
@@ -128,10 +128,10 @@ def test_get_variants_to_promotions_map_no_active_rules(product):
def test_get_variants_to_promotions_map_no_matching_rules(
- product_with_two_variants, variant, promotion_without_rules
+ product_with_two_variants, variant, catalogue_promotion_without_rules
):
# given
- promotion = promotion_without_rules
+ promotion = catalogue_promotion_without_rules
percentage_reward_value = Decimal("10")
rule = promotion.rules.create(
diff --git a/saleor/discount/tests/test_utils/test_update_rule_variant_relation.py b/saleor/discount/tests/test_utils/test_update_rule_variant_relation.py
index bbbf0fb8b9..e672d876fe 100644
--- a/saleor/discount/tests/test_utils/test_update_rule_variant_relation.py
+++ b/saleor/discount/tests/test_utils/test_update_rule_variant_relation.py
@@ -8,10 +8,10 @@ from ...utils import update_rule_variant_relation
def test_update_rule_variant_relation(
- promotion_without_rules, channel_USD, product_variant_list
+ catalogue_promotion_without_rules, channel_USD, product_variant_list
):
# given
- promotion = promotion_without_rules
+ promotion = catalogue_promotion_without_rules
variants = product_variant_list
PromotionRuleVariant = PromotionRule.variants.through
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 1786e2d418..07bab1f949 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -12,12 +12,19 @@ from django.utils import timezone
from prices import Money, TaxedMoney, fixed_discount, percentage_discount
from ..channel.models import Channel
+from ..checkout.base_calculations import (
+ base_checkout_delivery_price,
+ base_checkout_subtotal,
+)
+from ..checkout.models import Checkout
from ..core.taxes import zero_money
from ..core.utils.promo_code import InvalidPromoCode
from ..discount.models import VoucherCustomer
from ..product.models import Product, ProductVariant
-from . import DiscountType, PromotionRuleInfo
+from . import DiscountType, PromotionRuleInfo, RewardType
+from .interface import VariantPromotionRuleInfo, get_rule_translations
from .models import (
+ CheckoutDiscount,
CheckoutLineDiscount,
DiscountValueType,
NotApplicable,
@@ -30,7 +37,6 @@ from .models import (
if TYPE_CHECKING:
from ..account.models import User
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
- from ..discount.interface import VariantPromotionRuleInfo
from ..order.models import Order
from ..plugins.manager import PluginsManager
from ..product.managers import ProductVariantQueryset
@@ -327,6 +333,14 @@ def apply_discount_to_value(
def create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info: "CheckoutInfo",
+ lines_info: Iterable["CheckoutLineInfo"],
+):
+ create_discount_objects_for_catalogue_promotions(lines_info)
+ create_discount_objects_for_order_promotions(checkout_info, lines_info)
+
+
+def create_discount_objects_for_catalogue_promotions(
lines_info: Iterable["CheckoutLineInfo"],
):
line_discounts_to_create = []
@@ -386,7 +400,7 @@ def create_or_update_discount_objects_from_promotion_for_checkout(
line_discounts_to_create.append(line_discount)
line_info.discounts.append(line_discount)
else:
- _update_line_discount(
+ _update_discount(
rule,
rule_info,
rule_discount_amount,
@@ -438,9 +452,11 @@ def _get_discounts_that_are_not_valid_anymore(
def _get_rule_discount_amount(
- variant_listing_promotion_rule: "VariantChannelListingPromotionRule",
+ variant_listing_promotion_rule: Optional["VariantChannelListingPromotionRule"],
line_quantity: int,
) -> Decimal:
+ if not variant_listing_promotion_rule:
+ return Decimal("0.0")
discount_amount = variant_listing_promotion_rule.discount_amount
return discount_amount * line_quantity
@@ -463,13 +479,16 @@ def get_discount_translated_name(rule_info: "VariantPromotionRuleInfo"):
return None
-def _update_line_discount(
+def _update_discount(
rule: "PromotionRule",
rule_info: "VariantPromotionRuleInfo",
rule_discount_amount: Decimal,
- discount_to_update: "CheckoutLineDiscount",
+ discount_to_update: Union["CheckoutLineDiscount", "CheckoutDiscount"],
updated_fields: list[str],
):
+ if discount_to_update.promotion_rule_id != rule.id:
+ discount_to_update.promotion_rule_id = rule.id
+ updated_fields.append("promotion_rule_id")
if discount_to_update.value_type != rule.reward_value_type:
discount_to_update.value_type = (
rule.reward_value_type # type: ignore[assignment]
@@ -489,6 +508,173 @@ def _update_line_discount(
if discount_to_update.translated_name != translated_name:
discount_to_update.translated_name = translated_name
updated_fields.append("translated_name")
+ reason = prepare_promotion_discount_reason(
+ rule_info.promotion, get_sale_id(rule_info.promotion)
+ )
+ if discount_to_update.reason != reason:
+ discount_to_update.reason = reason
+ updated_fields.append("reason")
+
+
+def create_discount_objects_for_order_promotions(
+ checkout_info: "CheckoutInfo",
+ lines_info: Iterable["CheckoutLineInfo"],
+ *,
+ save: bool = False,
+):
+ # The base prices are required for order promotion discount qualification.
+ _set_checkout_base_prices(checkout_info, lines_info)
+
+ checkout = checkout_info.checkout
+
+ # Discount from order rules is applied only when the voucher is not set
+ if checkout.voucher_code:
+ _clear_checkout_discount(checkout_info, save)
+ return
+
+ rules = fetch_promotion_rules_for_checkout(checkout)
+ if not rules:
+ _clear_checkout_discount(checkout_info, save)
+ return
+
+ subtotal = checkout.base_subtotal
+ currency_code = checkout_info.channel.currency_code
+ rule_with_discount_amount = []
+ for rule in rules:
+ discount = rule.get_discount(currency_code)
+ price = zero_money(currency_code)
+ if rule.reward_type == RewardType.SUBTOTAL_DISCOUNT:
+ price = subtotal
+ discount_amount = price - discount(price)
+ rule_with_discount_amount.append((rule, discount_amount))
+
+ best_rule, best_discount_amount = max(rule_with_discount_amount, key=lambda x: x[1])
+ promotion = best_rule.promotion
+
+ _create_or_update_checkout_discount(
+ checkout,
+ checkout_info,
+ best_rule,
+ best_discount_amount,
+ currency_code,
+ promotion,
+ save,
+ )
+
+
+def _set_checkout_base_prices(checkout_info, lines_info):
+ """Set base checkout prices that includes only catalogue discounts."""
+ checkout = checkout_info.checkout
+ subtotal = base_checkout_subtotal(
+ lines_info, checkout_info.channel, checkout.currency, include_voucher=False
+ )
+ shipping_price = base_checkout_delivery_price(
+ checkout_info, lines_info, include_voucher=False
+ )
+ total = subtotal + shipping_price
+ is_update_needed = not (
+ checkout.base_subtotal == subtotal and checkout.base_total == total
+ )
+ if is_update_needed:
+ checkout.base_subtotal = subtotal
+ checkout.base_total = total
+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])
+
+
+def _clear_checkout_discount(checkout_info, save):
+ if checkout_info.discounts:
+ CheckoutDiscount.objects.filter(
+ checkout=checkout_info.checkout,
+ type=DiscountType.ORDER_PROMOTION,
+ ).delete()
+ checkout_info.discounts = [
+ discount
+ for discount in checkout_info.discounts
+ if discount.type != DiscountType.ORDER_PROMOTION
+ ]
+ checkout = checkout_info.checkout
+ if not checkout_info.voucher_code:
+ is_update_needed = not (
+ checkout.discount_amount == 0
+ and checkout.discount_name is None
+ and checkout.translated_discount_name is None
+ )
+ if is_update_needed:
+ checkout.discount_amount = 0
+ checkout.discount_name = None
+ checkout.translated_discount_name = None
+
+ if save and is_update_needed:
+ checkout.save(
+ update_fields=[
+ "discount_amount",
+ "discount_name",
+ "translated_discount_name",
+ ]
+ )
+
+
+def _create_or_update_checkout_discount(
+ checkout: "Checkout",
+ checkout_info: "CheckoutInfo",
+ best_rule: "PromotionRule",
+ best_discount_amount: Money,
+ currency_code: str,
+ promotion: "Promotion",
+ save: bool,
+):
+ translation_language_code = checkout.language_code
+ promotion_translation, rule_translation = get_rule_translations(
+ promotion, best_rule, translation_language_code
+ )
+ rule_info = VariantPromotionRuleInfo(
+ rule=best_rule,
+ variant_listing_promotion_rule=None,
+ promotion=promotion,
+ promotion_translation=promotion_translation,
+ rule_translation=rule_translation,
+ )
+ checkout_discount, created = checkout.discounts.get_or_create(
+ type=DiscountType.ORDER_PROMOTION,
+ defaults={
+ "checkout": checkout,
+ "promotion_rule": best_rule,
+ "value_type": best_rule.reward_value_type,
+ "value": best_rule.reward_value,
+ "amount_value": best_discount_amount.amount,
+ "currency": currency_code,
+ "name": get_discount_name(best_rule, promotion),
+ "translated_name": get_discount_translated_name(rule_info),
+ "reason": prepare_promotion_discount_reason(
+ promotion, get_sale_id(promotion)
+ ),
+ },
+ )
+
+ if not created:
+ fields_to_update: list[str] = []
+ _update_discount(
+ best_rule,
+ rule_info,
+ best_discount_amount.amount,
+ checkout_discount,
+ fields_to_update,
+ )
+ if fields_to_update:
+ checkout_discount.save(update_fields=fields_to_update)
+
+ checkout_info.discounts = [checkout_discount]
+ checkout.discount = best_discount_amount
+ checkout.discount_name = checkout_discount.name
+ checkout.translated_discount_name = checkout_discount.translated_name
+ if save:
+ checkout.save(
+ update_fields=[
+ "discount_amount",
+ "discount_name",
+ "translated_discount_name",
+ ]
+ )
def get_variants_to_promotion_rules_map(
@@ -518,7 +704,7 @@ def get_variants_to_promotion_rules_map(
rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)
rules_in_bulk = rules.in_bulk()
- for promotion_rule_variant in list(promotion_rule_variants.iterator()):
+ for promotion_rule_variant in promotion_rule_variants.iterator():
rule_id = promotion_rule_variant.promotionrule_id
rule = rules_in_bulk.get(rule_id)
# there is no rule when it is a part of inactive promotion
@@ -535,6 +721,37 @@ def get_variants_to_promotion_rules_map(
return rules_info_per_variant
+def fetch_promotion_rules_for_checkout(
+ checkout: Checkout,
+):
+ from ..graphql.discount.utils import PredicateObjectType, filter_qs_by_predicate
+
+ applicable_rules = []
+ promotions = Promotion.objects.active()
+ checkout_channel_id = checkout.channel_id
+ PromotionRuleChannels = PromotionRule.channels.through.objects.filter(
+ channel_id=checkout_channel_id
+ )
+ rules = PromotionRule.objects.filter(
+ Exists(promotions.filter(id=OuterRef("promotion_id"))),
+ Exists(PromotionRuleChannels.filter(promotionrule_id=OuterRef("id"))),
+ ).exclude(order_predicate={})
+
+ currency = checkout.channel.currency_code
+ checkout_qs = Checkout.objects.filter(pk=checkout.pk)
+ for rule in rules.iterator():
+ checkouts = filter_qs_by_predicate(
+ rule.order_predicate,
+ checkout_qs,
+ PredicateObjectType.CHECKOUT,
+ currency,
+ )
+ if checkouts.exists():
+ applicable_rules.append(rule)
+
+ return applicable_rules
+
+
def _get_rule_to_channel_ids_map(rules: QuerySet):
rule_to_channel_ids_map = defaultdict(list)
PromotionRuleChannel = PromotionRule.channels.through
diff --git a/saleor/graphql/channel/filters.py b/saleor/graphql/channel/filters.py
index 25fe3ae2fa..ec27c52109 100644
--- a/saleor/graphql/channel/filters.py
+++ b/saleor/graphql/channel/filters.py
@@ -1,3 +1,8 @@
def get_channel_slug_from_filter_data(filter_data: dict):
channel = filter_data.get("channel")
return str(channel) if channel else None
+
+
+def get_currency_from_filter_data(filter_data: dict):
+ currency = filter_data.get("currency")
+ return str(currency) if currency else None
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index e0c35e62a9..d9545cdc88 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -1283,7 +1283,7 @@ def test_channel_update_set_checkout_use_legacy_error_flow_without_permission(
assert_no_permission(response)
-def test_channel_update_checkout_and_order_settings_with_manage_orders(
+def test_channel_update_order_settings_with_manage_orders(
staff_api_client, channel_USD, permission_manage_orders
):
# given
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
index a4800f469e..9759b9da01 100644
--- a/saleor/graphql/checkout/dataloaders.py
+++ b/saleor/graphql/checkout/dataloaders.py
@@ -31,6 +31,7 @@ from ..account.dataloaders import AddressByIdLoader, UserByUserIdLoader
from ..channel.dataloaders import ChannelByIdLoader
from ..core.dataloaders import DataLoader
from ..discount.dataloaders import (
+ CheckoutDiscountByCheckoutIdLoader,
CheckoutLineDiscountsByCheckoutLineIdLoader,
PromotionByRuleIdLoader,
PromotionRuleByIdLoader,
@@ -421,7 +422,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
def batch_load(self, keys):
def with_checkout(data):
- checkouts, checkout_line_infos, manager = data
+ checkouts, checkout_line_infos, checkout_discounts, manager = data
from ..channel.dataloaders import ChannelByIdLoader
channel_pks = [checkout.channel_id for checkout in checkouts]
@@ -510,8 +511,12 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
}
checkout_info_map = {}
- for key, checkout, channel, checkout_lines in zip(
- keys, checkouts, channels, checkout_line_infos
+ for key, checkout, channel, checkout_lines, discounts in zip(
+ keys,
+ checkouts,
+ channels,
+ checkout_line_infos,
+ checkout_discounts,
):
shipping_method = shipping_method_map.get(
checkout.shipping_method_id
@@ -540,6 +545,7 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
],
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=discounts,
voucher=voucher_code.voucher if voucher_code else None,
voucher_code=voucher_code,
)
@@ -584,8 +590,9 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):
checkout_line_infos = CheckoutLinesInfoByCheckoutTokenLoader(
self.context
).load_many(keys)
+ discounts = CheckoutDiscountByCheckoutIdLoader(self.context).load_many(keys)
manager = get_plugin_manager_promise(self.context)
- return Promise.all([checkouts, checkout_line_infos, manager]).then(
+ return Promise.all([checkouts, checkout_line_infos, discounts, manager]).then(
with_checkout
)
diff --git a/saleor/graphql/checkout/filters.py b/saleor/graphql/checkout/filters.py
index 07e2de6587..b24cf1fb3c 100644
--- a/saleor/graphql/checkout/filters.py
+++ b/saleor/graphql/checkout/filters.py
@@ -1,11 +1,13 @@
from uuid import UUID
import django_filters
+from django.core.exceptions import ValidationError
from django.db.models import Exists, OuterRef, Q
from ...account.models import User
from ...checkout.models import Checkout
from ...payment.models import Payment
+from ..channel.filters import get_currency_from_filter_data
from ..channel.types import Channel
from ..core.doc_category import DOC_CATEGORY_CHECKOUT
from ..core.filters import (
@@ -17,8 +19,9 @@ from ..core.filters import (
)
from ..core.types import DateRangeInput, FilterInputObjectType
from ..core.utils import from_global_id_or_error
+from ..discount.filters import DiscountedObjectWhere
from ..utils import resolve_global_ids_to_primary_keys
-from ..utils.filters import filter_range_field
+from ..utils.filters import filter_range_field, filter_where_by_numeric_field
from .enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
@@ -148,3 +151,28 @@ class CheckoutFilterInput(FilterInputObjectType):
class Meta:
doc_category = DOC_CATEGORY_CHECKOUT
filterset_class = CheckoutFilter
+
+
+class CheckoutDiscountedObjectWhere(DiscountedObjectWhere):
+ class Meta:
+ model = Checkout
+ fields = ["base_subtotal_price", "base_total_price"]
+
+ def filter_base_subtotal_price(self, queryset, name, value):
+ currency = get_currency_from_filter_data(self.data)
+ return _filter_price(queryset, name, "base_subtotal_amount", value, currency)
+
+ def filter_base_total_price(self, queryset, name, value):
+ currency = get_currency_from_filter_data(self.data)
+ return _filter_price(queryset, name, "base_total_amount", value, currency)
+
+
+def _filter_price(qs, _, field_name, value, currency):
+ # We will have single channel/currency as the rule can applied only
+ # on channels with the same currencies
+ if not currency:
+ raise ValidationError(
+ "You must provide a currency to filter by price field.", code="required"
+ )
+ qs = qs.filter(currency=currency)
+ return filter_where_by_numeric_field(qs, field_name, value)
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index 605aadb81f..4032bd9ad7 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -197,12 +197,10 @@ class CheckoutLinesAdd(BaseMutation):
checkout_info = fetch_checkout_info(
checkout, [], manager, shipping_channel_listings
)
-
existing_lines_info, _ = fetch_checkout_lines(
checkout, skip_lines_with_unavailable_variants=False
)
input_lines_data = cls._get_grouped_lines_data(lines, existing_lines_info)
-
lines = cls.clean_input(
info,
checkout,
@@ -213,6 +211,7 @@ class CheckoutLinesAdd(BaseMutation):
manager,
replace,
)
+
update_checkout_shipping_method_if_invalid(checkout_info, lines)
invalidate_checkout_prices(checkout_info, lines, manager, save=True)
cls.call_event(manager.checkout_updated, checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
index 227058a787..3b9e003e50 100644
--- a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
@@ -105,7 +105,7 @@ class CheckoutRemovePromoCode(BaseMutation):
checkout_info,
lines,
manager,
- recalculate_discount=False,
+ recalculate_discount=True,
save=True,
)
cls.call_event(manager.checkout_updated, checkout)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 018a50629a..4a43aff158 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -412,7 +412,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(61):
+ with django_assert_num_queries(65):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -430,7 +430,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(61):
+ with django_assert_num_queries(65):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -681,7 +681,7 @@ def test_update_checkout_lines_with_reservations(
reservation_length=5,
)
- with django_assert_num_queries(75):
+ with django_assert_num_queries(81):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -695,7 +695,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(75):
+ with django_assert_num_queries(81):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -940,7 +940,7 @@ def test_add_checkout_lines_with_reservations(
new_lines.append({"quantity": 2, "variantId": variant_id})
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(74):
+ with django_assert_num_queries(80):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -953,7 +953,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(74):
+ with django_assert_num_queries(80):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index 72bedb1c25..0c4ca0a8b3 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -795,6 +795,32 @@ def test_checkout_add_category_code_checkout_on_promotion(
assert checkout.subtotal < subtotal_discounted
+def test_checkout_add_voucher_code_checkout_on_checkout_promotion_discount(
+ api_client, checkout_with_item_and_order_discount, voucher
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ checkout_discount = checkout.discounts.first()
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "promoCode": voucher.code,
+ }
+
+ # when
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ # then
+ assert not data["errors"]
+ assert data["checkout"]["token"] == str(checkout.token)
+ assert data["checkout"]["voucherCode"] == voucher.code
+ checkout.refresh_from_db()
+ assert not checkout.discounts.all()
+ assert checkout.discount_amount
+ assert checkout.discount_name == voucher.name
+ with pytest.raises(checkout_discount._meta.model.DoesNotExist):
+ checkout_discount.refresh_from_db()
+
+
def test_checkout_add_variant_voucher_code_apply_once_per_order(
api_client, checkout_with_items, voucher_specific_product_type
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 6dd32d8095..21b6804742 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -1039,7 +1039,7 @@ def test_checkout_with_voucher_complete_product_on_promotion(
payment_dummy,
address,
shipping_method,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
):
# given
code = voucher_percentage.codes.first()
@@ -1064,7 +1064,7 @@ def test_checkout_with_voucher_complete_product_on_promotion(
channel = checkout.channel
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -1102,8 +1102,8 @@ def test_checkout_with_voucher_complete_product_on_promotion(
promotion_rule=rule,
)
- promotion_without_rules.name = ""
- promotion_without_rules.save(update_fields=["name"])
+ catalogue_promotion_without_rules.name = ""
+ catalogue_promotion_without_rules.save(update_fields=["name"])
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
@@ -1161,7 +1161,7 @@ def test_checkout_with_voucher_complete_product_on_promotion(
assert line_discount.value_type == DiscountValueType.FIXED
assert line_discount.amount_value == reward_value * order_line.quantity
assert order_line.sale_id == graphene.Node.to_global_id(
- "Promotion", promotion_without_rules.id
+ "Promotion", catalogue_promotion_without_rules.id
)
assert order_line.unit_discount_reason == f"Promotion: {order_line.sale_id}"
@@ -1396,7 +1396,7 @@ def test_checkout_complete_with_voucher_single_use(
def test_checkout_complete_product_on_promotion(
user_api_client,
checkout_with_item,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
payment_dummy,
address,
shipping_method,
@@ -1420,7 +1420,7 @@ def test_checkout_complete_product_on_promotion(
channel = checkout.channel
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -1516,7 +1516,7 @@ def test_checkout_complete_product_on_promotion(
assert line_discount.amount_value == reward_value * order_line.quantity
assert order_line.sale_id == graphene.Node.to_global_id(
- "Promotion", promotion_without_rules.id
+ "Promotion", catalogue_promotion_without_rules.id
)
assert order_line.unit_discount_reason == f"Promotion: {order_line.sale_id}"
@@ -1537,7 +1537,7 @@ def test_checkout_complete_product_on_promotion(
def test_checkout_complete_product_on_old_sale(
user_api_client,
checkout_with_item,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
payment_dummy,
address,
shipping_method,
@@ -1561,11 +1561,11 @@ def test_checkout_complete_product_on_old_sale(
channel = checkout.channel
old_sale_id = 1
- promotion_without_rules.old_sale_id = old_sale_id
- promotion_without_rules.save(update_fields=["old_sale_id"])
+ catalogue_promotion_without_rules.old_sale_id = old_sale_id
+ catalogue_promotion_without_rules.save(update_fields=["old_sale_id"])
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -1661,7 +1661,7 @@ def test_checkout_complete_product_on_old_sale(
assert line_discount.amount_value == reward_value * order_line.quantity
assert order_line.sale_id == graphene.Node.to_global_id(
- "Sale", promotion_without_rules.old_sale_id
+ "Sale", catalogue_promotion_without_rules.old_sale_id
)
assert order_line.unit_discount_reason == f"Sale: {order_line.sale_id}"
@@ -1682,7 +1682,7 @@ def test_checkout_complete_product_on_old_sale(
def test_checkout_complete_multiple_rules_applied(
user_api_client,
checkout_with_item,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
payment_dummy,
address,
shipping_method,
@@ -1711,7 +1711,7 @@ def test_checkout_complete_multiple_rules_applied(
[
PromotionRule(
name="Percentage promotion rule 1",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.FIXED,
reward_value=reward_value_1,
catalogue_predicate={
@@ -1726,7 +1726,7 @@ def test_checkout_complete_multiple_rules_applied(
),
PromotionRule(
name="Percentage promotion rule 2",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.PERCENTAGE,
reward_value=reward_value_2,
catalogue_predicate={
@@ -1863,7 +1863,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
user_api_client,
checkout_with_item_and_voucher_specific_products,
voucher_specific_product_type,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
payment_dummy,
address,
shipping_method,
@@ -1892,7 +1892,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
channel = checkout.channel
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -1928,7 +1928,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
amount_value=reward_value,
currency=channel.currency_code,
promotion_rule=rule,
- name=promotion_without_rules.name,
+ name=catalogue_promotion_without_rules.name,
)
manager = get_plugins_manager(allow_replica=False)
@@ -1991,7 +1991,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
assert checkout_line_quantity == order_line.quantity
assert checkout_line_variant == order_line.variant
assert order_line.sale_id == graphene.Node.to_global_id(
- "Promotion", promotion_without_rules.id
+ "Promotion", catalogue_promotion_without_rules.id
)
unit_discount_reason = (
f"Voucher code: {voucher_specific_product_type.code}"
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 27e4198ac6..296b9f693c 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -1845,7 +1845,7 @@ def test_checkout_with_voucher_complete_product_on_sale(
user_api_client,
checkout_with_voucher_percentage,
voucher_percentage,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
address,
shipping_method,
transaction_events_generator,
@@ -1866,15 +1866,15 @@ def test_checkout_with_voucher_complete_product_on_sale(
voucher_percentage.save(update_fields=["usage_limit"])
old_sale_id = 1
- promotion_without_rules.old_sale_id = old_sale_id
- promotion_without_rules.save(update_fields=["old_sale_id"])
+ catalogue_promotion_without_rules.old_sale_id = old_sale_id
+ catalogue_promotion_without_rules.save(update_fields=["old_sale_id"])
checkout_line = checkout.lines.first()
checkout_line_variant = checkout_line.variant
channel = checkout.channel
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -1912,8 +1912,8 @@ def test_checkout_with_voucher_complete_product_on_sale(
promotion_rule=rule,
)
- promotion_without_rules.name = ""
- promotion_without_rules.save(update_fields=["name"])
+ catalogue_promotion_without_rules.name = ""
+ catalogue_promotion_without_rules.save(update_fields=["name"])
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
@@ -1953,7 +1953,7 @@ def test_checkout_with_voucher_complete_product_on_sale(
order_line.undiscounted_total_price - order_line.total_price
)
assert order_line.sale_id == graphene.Node.to_global_id(
- "Sale", promotion_without_rules.old_sale_id
+ "Sale", catalogue_promotion_without_rules.old_sale_id
)
assert order_line.unit_discount_reason == f"Sale: {order_line.sale_id}"
@@ -2047,7 +2047,7 @@ def test_checkout_with_voucher_on_specific_product_complete(
def test_checkout_complete_product_on_promotion(
user_api_client,
checkout_with_item,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
address,
shipping_method,
transaction_events_generator,
@@ -2069,7 +2069,7 @@ def test_checkout_complete_product_on_promotion(
channel = checkout.channel
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -2145,7 +2145,7 @@ def test_checkout_complete_product_on_promotion(
order_line.undiscounted_total_price - order_line.total_price
)
assert order_line.sale_id == graphene.Node.to_global_id(
- "Promotion", promotion_without_rules.id
+ "Promotion", catalogue_promotion_without_rules.id
)
assert not Checkout.objects.filter(
pk=checkout.pk
@@ -2157,7 +2157,7 @@ def test_checkout_complete_multiple_rules_applied(
checkout_with_item,
address,
shipping_method,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
transaction_events_generator,
transaction_item_generator,
):
@@ -2182,7 +2182,7 @@ def test_checkout_complete_multiple_rules_applied(
[
PromotionRule(
name="Percentage promotion rule 1",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.FIXED,
reward_value=reward_value_1,
catalogue_predicate={
@@ -2197,7 +2197,7 @@ def test_checkout_complete_multiple_rules_applied(
),
PromotionRule(
name="Percentage promotion rule 2",
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
reward_value_type=RewardValueType.PERCENTAGE,
reward_value=reward_value_2,
catalogue_predicate={
@@ -2303,7 +2303,7 @@ def test_checkout_complete_multiple_rules_applied(
)
assert order_line.sale_id == graphene.Node.to_global_id(
- "Promotion", promotion_without_rules.id
+ "Promotion", catalogue_promotion_without_rules.id
)
assert not Checkout.objects.filter(
pk=checkout.pk
@@ -2314,7 +2314,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
user_api_client,
checkout_with_item_and_voucher_specific_products,
voucher_specific_product_type,
- promotion_with_single_rule,
+ catalogue_promotion_with_single_rule,
address,
shipping_method,
transaction_events_generator,
@@ -2340,7 +2340,7 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
"ProductVariant", checkout_line_variant.id
)
- rule = promotion_with_single_rule.rules.first()
+ rule = catalogue_promotion_with_single_rule.rules.first()
predicate = {"variantPredicate": {"ids": [checkout_line_variant_id]}}
rule.catalogue_predicate = predicate
rule.save(update_fields=["catalogue_predicate"])
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 3bc1df93cb..966ca851bd 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -15,7 +15,7 @@ from .....checkout.utils import (
invalidate_checkout_prices,
recalculate_checkout_discount,
)
-from .....discount import RewardValueType
+from .....discount import RewardType, RewardValueType
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing
from .....warehouse import WarehouseClickAndCollectOption
@@ -142,7 +142,7 @@ def test_add_to_existing_line_with_sale_when_checkout_has_voucher(
stock,
voucher_percentage,
channel_USD,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
):
# given
@@ -161,7 +161,7 @@ def test_add_to_existing_line_with_sale_when_checkout_has_voucher(
# prepare promotion with 50% discount
reward_value = Decimal("50.00")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [graphene.Node.to_global_id("Product", variant.product.id)]
@@ -240,6 +240,214 @@ def test_add_to_existing_line_with_sale_when_checkout_has_voucher(
)
+def test_add_to_existing_line_catalogue_and_order_discount_applies(
+ user_api_client,
+ checkout_with_item,
+ stock,
+ channel_USD,
+ catalogue_promotion_without_rules,
+):
+ """Ensure that both catalogue and order discount are applied."""
+ # given
+ checkout = checkout_with_item
+ variant_unit_price = Decimal(100)
+ line = checkout.lines.first()
+ variant = line.variant
+
+ # prepare catalogue promotion with 50% discount
+ reward_value = Decimal("50.00")
+ rule = catalogue_promotion_without_rules.rules.create(
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", variant.product.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel_USD)
+
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+
+ variant_channel_listing.price_amount = variant_unit_price
+ discount_amount = variant_unit_price * reward_value / 100
+ variant_channel_listing.discounted_price_amount = (
+ variant_channel_listing.price_amount - discount_amount
+ )
+ variant_channel_listing.save(
+ update_fields=["discounted_price_amount", "price_amount"]
+ )
+
+ variant_channel_listing.variantlistingpromotionrule.create(
+ promotion_rule=rule,
+ discount_amount=discount_amount,
+ currency=channel_USD.currency_code,
+ )
+
+ # create order promotion discount
+ rule = catalogue_promotion_without_rules.rules.create(
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("50"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel_USD)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ line.refresh_from_db()
+ checkout.refresh_from_db()
+
+ variant_listing = variant.channel_listings.get(channel=checkout.channel)
+ base_unit_price = variant_listing.price_amount
+ discounted_unit_price = base_unit_price * Decimal("0.5")
+ # catalogue promotion 50% then order promotion 50%
+ expected_unit_price_after_all_discount = discounted_unit_price * Decimal("0.5")
+
+ expected_total_price = expected_unit_price_after_all_discount * line.quantity
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+
+ unit_price = data["checkout"]["lines"][0]["unitPrice"]["gross"]["amount"]
+ assert Decimal(unit_price) == expected_unit_price_after_all_discount
+ total_price = data["checkout"]["lines"][0]["totalPrice"]["gross"]["amount"]
+ assert Decimal(total_price) == expected_total_price
+ checkout_discount_amount = data["checkout"]["discount"]["amount"]
+ discount_amount = (
+ Decimal(discounted_unit_price) - expected_unit_price_after_all_discount
+ ) * line.quantity
+ assert Decimal(checkout_discount_amount) == discount_amount
+ assert checkout.discounts.count() == 1
+
+
+def test_add_to_existing_line_on_promotion_with_voucher_checkout_promotion_not_applies(
+ user_api_client,
+ checkout_with_item,
+ stock,
+ voucher_percentage,
+ channel_USD,
+ catalogue_promotion_without_rules,
+):
+ """Ensure that order promotion discount is not applied when the voucher is set."""
+ # given
+
+ # prepare voucher with 50% discount
+ voucher_percentage_value = 50
+ voucher_percentage.channel_listings.update(discount_value=voucher_percentage_value)
+
+ checkout = checkout_with_item
+ checkout.voucher_code = voucher_percentage.code
+ checkout.save()
+
+ variant_unit_price = Decimal(100)
+ line = checkout.lines.first()
+ variant = line.variant
+
+ # prepare promotion with 50% discount
+ reward_value = Decimal("50.00")
+ rule = catalogue_promotion_without_rules.rules.create(
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", variant.product.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel_USD)
+
+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
+
+ variant_channel_listing.price_amount = variant_unit_price
+ discount_amount = variant_unit_price * reward_value / 100
+ variant_channel_listing.discounted_price_amount = (
+ variant_channel_listing.price_amount - discount_amount
+ )
+ variant_channel_listing.save(
+ update_fields=["discounted_price_amount", "price_amount"]
+ )
+
+ variant_channel_listing.variantlistingpromotionrule.create(
+ promotion_rule=rule,
+ discount_amount=discount_amount,
+ currency=channel_USD.currency_code,
+ )
+
+ # create order promotion discount
+ rule = catalogue_promotion_without_rules.rules.create(
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("50"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel_USD)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+
+ line.refresh_from_db()
+ checkout.refresh_from_db()
+ assert not checkout.discounts.all()
+
+ # unit_price: 100, sale 50% then voucher 50% = 25
+ expected_unit_price_after_all_discount = Decimal(25)
+ expected_discount_per_single_item = Decimal(25)
+ unit_price = data["checkout"]["lines"][0]["unitPrice"]["gross"]["amount"]
+ assert Decimal(unit_price) == expected_unit_price_after_all_discount
+ total_price = data["checkout"]["lines"][0]["totalPrice"]["gross"]["amount"]
+ assert (
+ Decimal(total_price) == expected_unit_price_after_all_discount * line.quantity
+ )
+ checkout_discount_amount = data["checkout"]["discount"]["amount"]
+ # unit price is 50 USD, (after applying sale), then 50% voucher gives us a
+ # unit_price equal to 25 USD. The discount amount is 25 USD * quantity
+ assert (
+ Decimal(checkout_discount_amount)
+ == expected_discount_per_single_item * line.quantity
+ )
+
+
def test_checkout_lines_add_with_existing_variant_and_metadata(
user_api_client,
checkout_with_item,
@@ -724,6 +932,94 @@ def test_checkout_lines_add_existing_variant_override_previous_custom_price(
assert line.price_override == price
+def test_checkout_lines_add_custom_price_and_order_fixed_discount(
+ app_api_client,
+ checkout_with_item_and_order_discount,
+ permission_handle_checkouts,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ line = checkout.lines.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)
+ price = Decimal("13.11")
+ discount_amount = checkout.discount_amount
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_ADD,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ checkout.refresh_from_db()
+ line = checkout.lines.last()
+ total_price = price * line.quantity
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ assert data["checkout"]["discount"]["amount"] == discount_amount
+ assert line.price_override == price
+ assert checkout.discount_amount == discount_amount
+ assert checkout.subtotal.gross.amount == total_price - discount_amount
+ assert checkout.total.gross.amount == total_price - discount_amount
+
+
+def test_checkout_lines_add_custom_price_and_order_percentage_discount(
+ app_api_client,
+ checkout_with_item_and_order_discount,
+ permission_handle_checkouts,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ checkout_discount = checkout.discounts.first()
+ rule = checkout_discount.promotion_rule
+ rule.reward_value = 50
+ rule.reward_value_type = RewardValueType.PERCENTAGE
+ rule.save(update_fields=["reward_value", "reward_value_type"])
+
+ line = checkout.lines.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)
+ price = Decimal("13.11")
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_ADD,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ checkout.refresh_from_db()
+ line = checkout.lines.last()
+ total_price = price * line.quantity
+ discount_amount = total_price * Decimal("0.5")
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ assert Decimal(str(data["checkout"]["discount"]["amount"])) == Decimal(
+ discount_amount
+ )
+ assert line.price_override == price
+ assert checkout.discount_amount == discount_amount
+ assert checkout.subtotal.gross.amount == total_price - discount_amount
+ assert checkout.total.gross.amount == total_price - discount_amount
+
+
def test_checkout_lines_add_custom_price_app_no_perm(app_api_client, checkout, stock):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
index dfd7680c4e..bd89f1808a 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from decimal import Decimal
import graphene
from django.utils import timezone
@@ -6,6 +7,7 @@ from django.utils import timezone
from .....checkout import base_calculations
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....discount import RewardValueType
from .....plugins.manager import get_plugins_manager
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -20,8 +22,11 @@ MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """
message
}
checkout {
- token,
+ token
voucherCode
+ discount {
+ amount
+ }
giftCards {
id
last4CodeChars
@@ -297,6 +302,39 @@ def test_checkout_remove_voucher_code_invalidates_price(
assert data["checkout"]["totalPrice"]["gross"]["amount"] == expected_total
+def test_checkout_remove_voucher_code_checkout_promotion_discount_applied(
+ api_client, checkout_with_voucher, order_promotion_rule
+):
+ # given
+ checkout = checkout_with_voucher
+ reward_value = Decimal("5")
+ order_promotion_rule.reward_value = reward_value
+ order_promotion_rule.reward_value_type = RewardValueType.FIXED
+ order_promotion_rule.save(update_fields=["reward_value", "reward_value_type"])
+
+ assert checkout.voucher_code is not None
+ previous_checkout_last_change = checkout.last_change
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "promoCode": checkout.voucher_code,
+ }
+
+ # when
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ # then
+ checkout.refresh_from_db()
+ assert not data["errors"]
+ assert data["checkout"]["token"] == str(checkout.token)
+ assert data["checkout"]["voucherCode"] is None
+ assert data["checkout"]["discount"]["amount"] == reward_value
+ assert checkout.voucher_code is None
+ assert checkout.discount_amount == reward_value
+ assert checkout.last_change != previous_checkout_last_change
+ assert checkout.discounts.count() == 1
+
+
def test_with_active_problems_flow(
api_client,
checkout_with_problems,
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 471da32c67..45f95d069e 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -770,6 +770,9 @@ def test_order_from_checkout_with_voucher(
order_discount.amount_value
== (order.undiscounted_total - order.total).gross.amount
)
+ assert order_discount.type == DiscountType.VOUCHER
+ assert order_discount.voucher == voucher_percentage
+ assert order_discount.voucher_code == code.code
code.refresh_from_db()
assert code.used == voucher_used_count + 1
@@ -847,6 +850,9 @@ def test_order_from_checkout_with_voucher_apply_once_per_order(
order_discount.amount_value
== (order.undiscounted_total - order.total).gross.amount
)
+ assert order_discount.type == DiscountType.VOUCHER
+ assert order_discount.voucher == voucher_percentage
+ assert order_discount.voucher_code == code.code
code.refresh_from_db()
assert code.used == voucher_used_count + 1
@@ -911,6 +917,9 @@ def test_order_from_checkout_with_specific_product_voucher(
order_discount.amount_value
== (order.undiscounted_total - order.total).gross.amount
)
+ assert order_discount.type == DiscountType.VOUCHER
+ assert order_discount.voucher == voucher_specific_product_type
+ assert order_discount.voucher_code == code.code
code.refresh_from_db()
assert code.used == voucher_used_count + 1
@@ -956,7 +965,7 @@ def test_order_from_checkout_voucher_not_increase_uses_on_preprocess_creation_fa
assert code.used == 0
-def test_order_from_checkout_on_promotion(
+def test_order_from_checkout_on_catalogue_promotion(
app_api_client,
checkout_with_item_on_promotion,
permission_handle_checkouts,
@@ -988,7 +997,6 @@ def test_order_from_checkout_on_promotion(
assert not data["errors"]
order = Order.objects.first()
-
assert order.status == OrderStatus.UNCONFIRMED
assert order.origin == OrderOrigin.CHECKOUT
assert not order.original
@@ -1003,6 +1011,52 @@ def test_order_from_checkout_on_promotion(
assert (
discount.amount_value == (order.undiscounted_total - order.total).gross.amount
)
+ assert not order.discounts.first()
+
+
+def test_order_from_checkout_on_order_promotion(
+ app_api_client,
+ checkout_with_item_and_order_discount,
+ permission_handle_checkouts,
+ permission_manage_checkouts,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts, permission_manage_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order = Order.objects.first()
+ assert order.status == OrderStatus.UNCONFIRMED
+ assert order.origin == OrderOrigin.CHECKOUT
+ assert not order.original
+
+ order_discount = order.discounts.first()
+ assert order_discount.promotion_rule
+ assert (
+ order_discount.amount_value
+ == (order.undiscounted_total - order.total).gross.amount
+ )
+ assert order_discount.type == DiscountType.ORDER_PROMOTION
def test_order_from_checkout_multiple_rules_applied(
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index c804bab567..6c566b35c6 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -1469,6 +1469,9 @@ QUERY_CHECKOUT_PRICES = """
checkout(id: $id) {
displayGrossPrices
token
+ discount {
+ amount
+ }
totalPrice {
currency
gross {
@@ -1757,6 +1760,57 @@ def test_checkout_prices_with_promotion(
assert line_total_price.gross.amount < undiscounted_total_price
+def test_checkout_prices_with_order_promotion(
+ user_api_client, checkout_with_item_and_order_discount
+):
+ # given
+ query = QUERY_CHECKOUT_PRICES
+ checkout = checkout_with_item_and_order_discount
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+ assert len(data["lines"]) == checkout.lines.count()
+
+ line = checkout.lines.first()
+ variant = line.variant
+ variant_listing = variant.channel_listings.get(channel=checkout.channel)
+ unit_price = variant.get_price(variant_listing)
+ subtotal_price = unit_price * line.quantity
+ shipping_price = base_calculations.base_checkout_delivery_price(
+ checkout_info, lines
+ )
+ total_price = subtotal_price + shipping_price
+ discount_amount = checkout.discounts.first().amount_value
+
+ assert data["discount"]["amount"] == checkout.discount_amount
+ assert data["totalPrice"]["gross"]["amount"] == (
+ total_price.amount - discount_amount
+ )
+ assert data["subtotalPrice"]["gross"]["amount"] == (
+ subtotal_price.amount - discount_amount
+ )
+ assert str(data["lines"][0]["unitPrice"]["gross"]["amount"]) == str(
+ round((subtotal_price.amount - discount_amount) / line.quantity, 2)
+ )
+ assert (
+ data["lines"][0]["totalPrice"]["gross"]["amount"]
+ == subtotal_price.amount - discount_amount
+ )
+
+ assert data["lines"][0]["undiscountedUnitPrice"]["amount"] == unit_price.amount
+ assert data["lines"][0]["undiscountedTotalPrice"]["amount"] == subtotal_price.amount
+
+
def test_checkout_display_gross_prices_use_default(user_api_client, checkout_with_item):
# given
variables = {"id": to_global_id_or_none(checkout_with_item)}
diff --git a/saleor/graphql/checkout/tests/test_checkout_filters.py b/saleor/graphql/checkout/tests/test_checkout_filters.py
index ed9a2d114d..b27c2f595b 100644
--- a/saleor/graphql/checkout/tests/test_checkout_filters.py
+++ b/saleor/graphql/checkout/tests/test_checkout_filters.py
@@ -4,14 +4,18 @@ from decimal import Decimal
import graphene
import pytest
+from django.core.exceptions import ValidationError
from freezegun import freeze_time
+from prices import Money
from ....account.models import User
from ....checkout.models import Checkout
from ....checkout.payment_utils import update_checkout_payment_statuses
from ....payment.models import ChargeStatus, Payment
+from ...core.connection import where_filter_qs
from ...tests.utils import get_graphql_content
from ..enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
+from ..filters import CheckoutDiscountedObjectWhere
@pytest.fixture
@@ -608,3 +612,257 @@ def test_checkouts_query_with_filter_charge_status(
# then
content = get_graphql_content(response)
assert content["data"]["checkouts"]["totalCount"] == expected_count
+
+
+def test_filtering_checkout_discounted_object_where_by_base_total_price_range(
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+
+ currency = checkout.currency
+ subtotal_price = Money("20", currency)
+ total_price = Money("30", currency)
+ checkout.base_total = total_price
+ checkout.base_subtotal = subtotal_price
+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])
+
+ Checkout.objects.create(
+ currency=currency,
+ user=checkout.user,
+ channel=checkout.channel,
+ base_total=Money("15", currency),
+ base_subtotal=Money("10", currency),
+ )
+
+ qs = Checkout.objects.all()
+ predicate_data = {
+ "currency": currency,
+ "base_total_price": {
+ "range": {
+ "gte": 20,
+ }
+ },
+ }
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ CheckoutDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == 1
+ assert result.first() == checkout
+
+
+def test_filtering_checkout_discounted_object_where_by_base_total_price_one_of(
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+
+ currency = checkout.currency
+ subtotal_price = Money("20", currency)
+ total_price = Money("30", currency)
+ checkout.base_total = total_price
+ checkout.base_subtotal = subtotal_price
+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])
+
+ another_checkout = Checkout.objects.create(
+ currency=currency,
+ user=checkout.user,
+ channel=checkout.channel,
+ base_total=Money("15", currency),
+ base_subtotal=Money("10", currency),
+ )
+
+ qs = Checkout.objects.all()
+ predicate_data = {"currency": currency, "base_total_price": {"one_of": [15, 40]}}
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ CheckoutDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == 1
+ assert result.first() == another_checkout
+
+
+def test_filtering_checkout_discounted_object_where_by_base_total_currency_not_given(
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+
+ currency = checkout.currency
+ subtotal_price = Money("20", currency)
+ total_price = Money("30", currency)
+ checkout.base_total = total_price
+ checkout.base_subtotal = subtotal_price
+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])
+
+ Checkout.objects.create(
+ currency=currency,
+ user=checkout.user,
+ channel=checkout.channel,
+ base_total=Money("15", currency),
+ base_subtotal=Money("10", currency),
+ )
+
+ qs = Checkout.objects.all()
+ predicate_data = {
+ "base_total_price": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+
+ # when
+ with pytest.raises(ValidationError) as validation_error:
+ where_filter_qs(
+ qs,
+ {},
+ CheckoutDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert validation_error.value.code == "required"
+
+
+def test_filtering_checkout_discounted_object_where_by_base_subtotal_price_range(
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+
+ currency = checkout.currency
+ subtotal_price = Money("20", currency)
+ total_price = Money("30", currency)
+ checkout.base_total = total_price
+ checkout.base_subtotal = subtotal_price
+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])
+
+ another_checkout = Checkout.objects.create(
+ currency=currency,
+ user=checkout.user,
+ channel=checkout.channel,
+ base_total=Money("15", currency),
+ base_subtotal=Money("10", currency),
+ )
+
+ qs = Checkout.objects.all()
+ predicate_data = {
+ "currency": currency,
+ "base_subtotal_price": {
+ "range": {
+ "lte": 12,
+ }
+ },
+ }
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ CheckoutDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == 1
+ assert result.first() == another_checkout
+
+
+def test_filtering_checkout_discounted_object_where_by_base_subtotal_price_one_of(
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+
+ currency = checkout.currency
+ subtotal_price = Money("20", currency)
+ total_price = Money("30", currency)
+ checkout.base_total = total_price
+ checkout.base_subtotal = subtotal_price
+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])
+
+ Checkout.objects.create(
+ currency=currency,
+ user=checkout.user,
+ channel=checkout.channel,
+ base_total=Money("15", currency),
+ base_subtotal=Money("10", currency),
+ )
+
+ qs = Checkout.objects.all()
+ predicate_data = {"currency": currency, "base_subtotal_price": {"one_of": [15, 20]}}
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ CheckoutDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == 1
+ assert result.first() == checkout
+
+
+def test_filtering_checkout_discounted_object_where_by_base_subtotal_currency_not_given(
+ checkout_with_item,
+):
+ # given
+ checkout = checkout_with_item
+
+ currency = checkout.currency
+ subtotal_price = Money("20", currency)
+ total_price = Money("30", currency)
+ checkout.base_total = total_price
+ checkout.base_subtotal = subtotal_price
+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])
+
+ Checkout.objects.create(
+ currency=currency,
+ user=checkout.user,
+ channel=checkout.channel,
+ base_total=Money("15", currency),
+ base_subtotal=Money("10", currency),
+ )
+
+ qs = Checkout.objects.all()
+ predicate_data = {
+ "base_subtotal_price": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+
+ # when
+ with pytest.raises(ValidationError) as validation_error:
+ where_filter_qs(
+ qs,
+ {},
+ CheckoutDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert validation_error.value.code == "required"
diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.py
index a0b1a7da6c..6e5be42d23 100644
--- a/saleor/graphql/discount/dataloaders.py
+++ b/saleor/graphql/discount/dataloaders.py
@@ -8,6 +8,7 @@ from promise import Promise
from ...channel.models import Channel
from ...discount.interface import VoucherInfo
from ...discount.models import (
+ CheckoutDiscount,
CheckoutLineDiscount,
OrderDiscount,
Promotion,
@@ -243,6 +244,21 @@ class CheckoutLineDiscountsByCheckoutLineIdLoader(DataLoader):
return [discount_map.get(checkout_line_id, []) for checkout_line_id in keys]
+class CheckoutDiscountByCheckoutIdLoader(DataLoader):
+ context_key = "checkout_discount_by_checkout_id"
+
+ def batch_load(self, keys):
+ checkout_line_discounts = CheckoutDiscount.objects.using(
+ self.database_connection_name
+ ).filter(checkout_id__in=keys)
+ checkout_line_discounts_map = defaultdict(list)
+ for discount in checkout_line_discounts:
+ checkout_line_discounts_map[discount.checkout_id].append(discount)
+ return [
+ checkout_line_discounts_map.get(checkout_id, []) for checkout_id in keys
+ ]
+
+
class PromotionRulesByPromotionIdLoader(DataLoader):
context_key = "promotion_rules_by_promotion_id"
diff --git a/saleor/graphql/discount/enums.py b/saleor/graphql/discount/enums.py
index d3894aa626..6b626eea7b 100644
--- a/saleor/graphql/discount/enums.py
+++ b/saleor/graphql/discount/enums.py
@@ -4,6 +4,8 @@ from ...discount import (
DiscountType,
DiscountValueType,
PromotionEvents,
+ PromotionType,
+ RewardType,
RewardValueType,
VoucherType,
error_codes,
@@ -16,6 +18,10 @@ OrderDiscountTypeEnum = to_enum(DiscountType, type_name="OrderDiscountType")
OrderDiscountTypeEnum.doc_category = DOC_CATEGORY_DISCOUNTS
RewardValueTypeEnum = to_enum(RewardValueType, type_name="RewardValueTypeEnum")
RewardValueTypeEnum.doc_category = DOC_CATEGORY_DISCOUNTS
+RewardTypeEnum = to_enum(RewardType, type_name="RewardTypeEnum")
+RewardTypeEnum.doc_category = DOC_CATEGORY_DISCOUNTS
+PromotionTypeEnum = to_enum(PromotionType, type_name="PromotionTypeEnum")
+PromotionTypeEnum.doc_category = DOC_CATEGORY_DISCOUNTS
PromotionEventsEnum = to_enum(PromotionEvents, type_name="PromotionEventsEnum")
PromotionEventsEnum.doc_category = DOC_CATEGORY_DISCOUNTS
diff --git a/saleor/graphql/discount/filters.py b/saleor/graphql/discount/filters.py
index 43eeb6e431..7d8696dec0 100644
--- a/saleor/graphql/discount/filters.py
+++ b/saleor/graphql/discount/filters.py
@@ -23,14 +23,21 @@ from ..core.filters import (
ObjectTypeFilter,
ObjectTypeWhereFilter,
OperationObjectTypeWhereFilter,
+ WhereFilterSet,
)
from ..core.types import (
+ BaseInputObjectType,
DateTimeFilterInput,
DateTimeRangeInput,
IntRangeInput,
+ NonNullList,
StringFilterInput,
)
-from ..core.types.filter_input import WhereInputObjectType
+from ..core.types.filter_input import (
+ DecimalFilterInput,
+ FilterInputDescriptions,
+ WhereInputObjectType,
+)
from ..utils.filters import (
filter_by_id,
filter_by_ids,
@@ -38,7 +45,12 @@ from ..utils.filters import (
filter_where_by_string_field,
filter_where_range_field,
)
-from .enums import DiscountStatusEnum, DiscountValueTypeEnum, VoucherDiscountType
+from .enums import (
+ DiscountStatusEnum,
+ DiscountValueTypeEnum,
+ PromotionTypeEnum,
+ VoucherDiscountType,
+)
def filter_status(
@@ -150,6 +162,18 @@ class SaleFilter(MetadataFilterBase):
fields = ["status", "sale_type", "started", "search"]
+class PromotionTypeEnumFilterInput(BaseInputObjectType):
+ eq = PromotionTypeEnum(description=FilterInputDescriptions.EQ, required=False)
+ one_of = NonNullList(
+ PromotionTypeEnum,
+ description=FilterInputDescriptions.ONE_OF,
+ required=False,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_DISCOUNTS
+
+
class PromotionWhere(MetadataWhereFilterBase):
ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("Promotion"))
name = OperationObjectTypeWhereFilter(
@@ -168,6 +192,9 @@ class PromotionWhere(MetadataWhereFilterBase):
help_text="Filter promotions by start date.",
)
is_old_sale = BooleanWhereFilter(method="filter_is_old_sale")
+ type = OperationObjectTypeWhereFilter(
+ input_class=PromotionTypeEnumFilterInput, method="filter_type"
+ )
@staticmethod
def filter_promotion_name(qs, _, value):
@@ -185,8 +212,34 @@ class PromotionWhere(MetadataWhereFilterBase):
def filter_is_old_sale(qs, _, value):
return qs.exclude(old_sale_id__isnull=value)
+ @staticmethod
+ def filter_type(qs, _, value):
+ return filter_where_by_string_field(qs, "type", value)
+
class PromotionWhereInput(WhereInputObjectType):
class Meta:
doc_category = DOC_CATEGORY_DISCOUNTS
filterset_class = PromotionWhere
+
+
+class DiscountedObjectWhere(WhereFilterSet):
+ base_subtotal_price = OperationObjectTypeWhereFilter(
+ input_class=DecimalFilterInput,
+ method="filter_base_subtotal_price",
+ help_text="Filter by the base subtotal price.",
+ )
+ base_total_price = OperationObjectTypeWhereFilter(
+ input_class=DecimalFilterInput,
+ method="filter_base_total_price",
+ help_text="Filter by the base total price.",
+ )
+
+ class Meta:
+ abstract = True
+
+
+class DiscountedObjectWhereInput(WhereInputObjectType):
+ class Meta:
+ doc_category = DOC_CATEGORY_DISCOUNTS
+ filterset_class = DiscountedObjectWhere
diff --git a/saleor/graphql/discount/inputs.py b/saleor/graphql/discount/inputs.py
index 583bf99ab5..384de1f648 100644
--- a/saleor/graphql/discount/inputs.py
+++ b/saleor/graphql/discount/inputs.py
@@ -1,15 +1,17 @@
import graphene
+from ..core.descriptions import ADDED_IN_319, PREVIEW_FEATURE
from ..core.doc_category import DOC_CATEGORY_DISCOUNTS
from ..core.scalars import JSON, PositiveDecimal
from ..core.types import BaseInputObjectType, NonNullList
+from ..discount.filters import DiscountedObjectWhereInput
from ..product.filters import (
CategoryWhereInput,
CollectionWhereInput,
ProductVariantWhereInput,
ProductWhereInput,
)
-from .enums import RewardValueTypeEnum
+from .enums import RewardTypeEnum, RewardValueTypeEnum
class PredicateInputObjectType(BaseInputObjectType):
@@ -63,6 +65,16 @@ class CataloguePredicateInput(PredicateInputObjectType):
doc_category = DOC_CATEGORY_DISCOUNTS
+class OrderPredicateInput(PredicateInputObjectType):
+ discounted_object_predicate = graphene.Field(
+ DiscountedObjectWhereInput,
+ description="Defines the conditions related to checkout and order objects.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_DISCOUNTS
+
+
class PromotionRuleBaseInput(BaseInputObjectType):
name = graphene.String(description="Promotion rule name.")
description = JSON(description="Promotion rule description.")
@@ -72,6 +84,13 @@ class PromotionRuleBaseInput(BaseInputObjectType):
"for the reward to be applied."
),
)
+ order_predicate = graphene.Field(
+ OrderPredicateInput,
+ description=(
+ "Defines the conditions on the checkout/draft order level that must be met "
+ "for the reward to be applied." + ADDED_IN_319 + PREVIEW_FEATURE
+ ),
+ )
reward_value_type = RewardValueTypeEnum(
description=(
"Defines the promotion rule reward value type. "
@@ -83,3 +102,8 @@ class PromotionRuleBaseInput(BaseInputObjectType):
"Defines the discount value. Required when catalogue predicate is provided."
),
)
+ reward_type = RewardTypeEnum(
+ description="Defines the reward type of the promotion rule."
+ + ADDED_IN_319
+ + PREVIEW_FEATURE
+ )
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_create.py b/saleor/graphql/discount/mutations/promotion/promotion_create.py
index 5c0b8bd8df..930377f810 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_create.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_create.py
@@ -3,12 +3,14 @@ from datetime import datetime
import graphene
import pytz
+from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
+from django.db.models import Q
from graphql.error import GraphQLError
from .....channel import models as channel_models
-from .....discount import events, models
+from .....discount import PromotionType, events, models
from .....permission.enums import DiscountPermissions
from .....plugins.manager import PluginsManager
from .....product.tasks import update_products_discounted_prices_of_promotion_task
@@ -16,7 +18,7 @@ from .....webhook.event_types import WebhookEventAsyncType
from ....app.dataloaders import get_app_promise
from ....channel.types import Channel
from ....core import ResolveInfo
-from ....core.descriptions import ADDED_IN_317, PREVIEW_FEATURE
+from ....core.descriptions import ADDED_IN_317, ADDED_IN_319, PREVIEW_FEATURE
from ....core.doc_category import DOC_CATEGORY_DISCOUNTS
from ....core.mutations import ModelMutation
from ....core.scalars import JSON
@@ -25,7 +27,7 @@ from ....core.utils import WebhookEventInfo
from ....core.validators import validate_end_is_after_start
from ....plugins.dataloaders import get_plugin_manager_promise
from ....utils import get_nodes
-from ...enums import PromotionCreateErrorCode
+from ...enums import PromotionCreateErrorCode, PromotionTypeEnum
from ...inputs import PromotionRuleBaseInput
from ...types import Promotion
from .validators import clean_promotion_rule
@@ -36,6 +38,12 @@ class PromotionCreateError(Error):
index = graphene.Int(
description="Index of an input list item that caused the error."
)
+ rules_limit = graphene.Int(
+ description="Limit of rules with orderPredicate defined."
+ )
+ exceed_by = graphene.Int(
+ description="Number of rules with orderPredicate defined exceeding the limit."
+ )
class PromotionRuleInput(PromotionRuleBaseInput):
@@ -60,6 +68,16 @@ class PromotionInput(BaseInputObjectType):
class PromotionCreateInput(PromotionInput):
name = graphene.String(description="Promotion name.", required=True)
+ type = PromotionTypeEnum(
+ description=(
+ "Defines the promotion type. Implicate the required promotion rules "
+ "predicate type and whether the promotion rules will give the catalogue "
+ "or order discount. "
+ "\n\nThe default value is `Catalogue`."
+ "\n\nThis field will be required from Saleor 3.20." + ADDED_IN_319
+ ),
+ required=False,
+ )
rules = NonNullList(PromotionRuleInput, description="List of promotion rules.")
class Meta:
@@ -105,8 +123,9 @@ class PromotionCreate(ModelMutation):
error.code = PromotionCreateErrorCode.INVALID.value
errors["end_date"].append(error)
+ promotion_type = cleaned_input.get("type", PromotionType.CATALOGUE)
if rules := cleaned_input.get("rules"):
- cleaned_rules, errors = cls.clean_rules(info, rules, errors)
+ cleaned_rules, errors = cls.clean_rules(info, rules, promotion_type, errors)
cleaned_input["rules"] = cleaned_rules
if errors:
@@ -119,14 +138,37 @@ class PromotionCreate(ModelMutation):
cls,
info: ResolveInfo,
rules_data: dict,
+ promotion_type: str,
errors: defaultdict[str, list[ValidationError]],
) -> tuple[list, defaultdict[str, list[ValidationError]]]:
cleaned_rules = []
+ if promotion_type == PromotionType.ORDER:
+ rules_limit = settings.ORDER_RULES_LIMIT
+ order_rules_count = models.PromotionRule.objects.filter(
+ ~Q(order_predicate={})
+ ).count()
+ exceed_by = order_rules_count + len(rules_data) - int(rules_limit)
+ if exceed_by > 0:
+ raise ValidationError(
+ {
+ "rules": ValidationError(
+ "Number of rules with orderPredicate has reached the limit",
+ code=PromotionCreateErrorCode.RULES_NUMBER_LIMIT.value,
+ params={
+ "rules_limit": rules_limit,
+ "exceed_by": exceed_by,
+ },
+ )
+ }
+ )
+
for index, rule_data in enumerate(rules_data):
if channel_ids := rule_data.get("channels"):
channels = cls.clean_channels(info, channel_ids, index, errors)
rule_data["channels"] = channels
- clean_promotion_rule(rule_data, errors, PromotionCreateErrorCode, index)
+ clean_promotion_rule(
+ rule_data, promotion_type, errors, PromotionCreateErrorCode, index
+ )
cleaned_rules.append(rule_data)
return cleaned_rules, errors
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
index 84ffedb353..ef6cb4ab78 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py
@@ -31,6 +31,12 @@ class PromotionRuleCreateInput(PromotionRuleInput):
class PromotionRuleCreateError(Error):
code = PromotionRuleCreateErrorCode(description="The error code.", required=True)
+ rules_limit = graphene.Int(
+ description="Limit of rules with orderPredicate defined."
+ )
+ exceed_by = graphene.Int(
+ description="Number of rules with orderPredicate defined exceeding the limit."
+ )
class PromotionRuleCreate(ModelMutation):
@@ -60,7 +66,15 @@ class PromotionRuleCreate(ModelMutation):
cleaned_input = super().clean_input(info, instance, data, **kwargs)
errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
- clean_promotion_rule(cleaned_input, errors, PromotionRuleCreateErrorCode)
+ promotion = cleaned_input["promotion"]
+ promotion_type = promotion.type
+
+ clean_promotion_rule(
+ cleaned_input,
+ promotion_type,
+ errors,
+ PromotionRuleCreateErrorCode,
+ )
if errors:
raise ValidationError(errors)
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
index 9992697c2f..f811bf9f5d 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py
@@ -1,8 +1,10 @@
+from collections import defaultdict
+
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
-from .....discount import RewardValueType, events, models
+from .....discount import events, models
from .....discount.utils import get_current_products_for_rules
from .....permission.enums import DiscountPermissions
from .....product.tasks import update_discounted_prices_task
@@ -22,9 +24,7 @@ from ...types import PromotionRule
from ...utils import get_products_for_rule
from ..utils import clear_promotion_old_sale_id
from .validators import (
- clean_fixed_discount_value,
- clean_percentage_discount_value,
- clean_predicate,
+ clean_promotion_rule,
)
@@ -102,89 +102,17 @@ class PromotionRuleUpdate(ModelMutation):
error.code = PromotionRuleUpdateErrorCode.DUPLICATED_INPUT_ITEM.value
raise ValidationError({"addChannels": error, "removeChannels": error})
cleaned_input = super().clean_input(info, instance, data, **kwargs)
- cls.clean_reward(instance, cleaned_input)
- if catalogue_predicate := cleaned_input.get("catalogue_predicate"):
- try:
- cleaned_input["catalogue_predicate"] = clean_predicate(
- catalogue_predicate, PromotionRuleUpdateErrorCode
- )
- except ValidationError as error:
- raise ValidationError({"catalogue_predicate": error})
- return cleaned_input
-
- @classmethod
- def clean_reward(cls, instance, cleaned_input):
- """Validate reward value and reward value type.
-
- - Fixed reward value type requires channels with the same currency code
- to be specified.
- - Validate price precision for fixed reward value.
- - Check if percentage reward value is not above 100.
- """
- channel_currencies = set(
- instance.channels.values_list("currency_code", flat=True)
+ errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
+ cleaned_input = clean_promotion_rule(
+ cleaned_input,
+ instance.promotion.type,
+ errors,
+ PromotionRuleUpdateErrorCode,
+ instance=instance,
)
- if remove_channels := cleaned_input.get("remove_channels"):
- channel_currencies = channel_currencies - {
- channel.currency_code for channel in remove_channels
- }
- if add_channels := cleaned_input.get("add_channels"):
- channel_currencies.update(
- [channel.currency_code for channel in add_channels]
- )
-
- if "reward_value" in cleaned_input or "reward_value_type" in cleaned_input:
- reward_value = cleaned_input.get("reward_value") or instance.reward_value
- reward_value_type = (
- cleaned_input.get("reward_value_type") or instance.reward_value_type
- )
- if reward_value_type == RewardValueType.FIXED:
- if not channel_currencies:
- field = (
- "reward_value_type"
- if "reward_value_type" in cleaned_input
- else "remove_channels"
- )
- raise ValidationError(
- {
- field: ValidationError(
- "Channels must be specified for FIXED rewardValueType.",
- code=PromotionRuleUpdateErrorCode.MISSING_CHANNELS.value,
- )
- }
- )
- if len(channel_currencies) > 1:
- field = (
- "reward_value_type"
- if "reward_value_type" in cleaned_input
- else "add_channels"
- )
- error_code = PromotionRuleUpdateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.value
- raise ValidationError(
- {
- field: ValidationError(
- "Channels must have the same currency code "
- "for FIXED rewardValueType.",
- code=error_code,
- )
- }
- )
- currency = channel_currencies.pop()
- try:
- clean_fixed_discount_value(
- reward_value,
- PromotionRuleUpdateErrorCode.INVALID_PRECISION.value,
- currency,
- )
- except ValidationError as error:
- raise ValidationError({"reward_value": error})
- elif reward_value_type == RewardValueType.PERCENTAGE:
- try:
- clean_percentage_discount_value(
- reward_value, PromotionRuleUpdateErrorCode.INVALID.value
- )
- except ValidationError as error:
- raise ValidationError({"reward_value": error})
+ if errors:
+ raise ValidationError(errors)
+ return cleaned_input
@classmethod
def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):
diff --git a/saleor/graphql/discount/mutations/promotion/validators.py b/saleor/graphql/discount/mutations/promotion/validators.py
index 0292f5b63d..cffe8c686e 100644
--- a/saleor/graphql/discount/mutations/promotion/validators.py
+++ b/saleor/graphql/discount/mutations/promotion/validators.py
@@ -1,30 +1,160 @@
from typing import TYPE_CHECKING, Union
+from django.conf import settings
from django.core.exceptions import ValidationError
+from django.db.models import Q
from graphene.utils.str_converters import to_camel_case
-from .....discount import RewardValueType
+from .....discount import PromotionType, RewardValueType
+from .....discount.models import PromotionRule
from ....core.validators import validate_price_precision
if TYPE_CHECKING:
from decimal import Decimal
-def clean_promotion_rule(cleaned_input, errors, error_class, index=None):
- if "catalogue_predicate" not in cleaned_input:
- errors["catalogue_predicate"].append(
+def clean_promotion_rule(
+ cleaned_input, promotion_type, errors, error_class, index=None, instance=None
+):
+ catalogue_predicate = cleaned_input.get("catalogue_predicate")
+ order_predicate = cleaned_input.get("order_predicate")
+ if instance:
+ catalogue_predicate = catalogue_predicate or instance.catalogue_predicate
+ order_predicate = order_predicate or instance.order_predicate
+ invalid_predicates = _clean_predicates(
+ catalogue_predicate,
+ order_predicate,
+ errors,
+ error_class,
+ index,
+ promotion_type,
+ )
+ if not invalid_predicates:
+ channel_currencies = _get_channel_currencies(cleaned_input, instance)
+ _clean_catalogue_predicate(
+ cleaned_input, catalogue_predicate, errors, error_class, index, instance
+ )
+ _clean_order_predicate(
+ cleaned_input,
+ order_predicate,
+ channel_currencies,
+ errors,
+ error_class,
+ index,
+ instance,
+ )
+ _clean_reward(
+ cleaned_input,
+ catalogue_predicate,
+ order_predicate,
+ channel_currencies,
+ errors,
+ error_class,
+ index,
+ instance,
+ )
+
+ return cleaned_input
+
+
+def _clean_predicates(
+ catalogue_predicate,
+ order_predicate,
+ errors,
+ error_class,
+ index,
+ promotion_type,
+):
+ """Validate if predicates are provided and if they aren't mixed.
+
+ - At least one predicate is required - `catalogue` or `order` predicate.
+ - Promotion can have only one predicate type, raise error if there are mixed.
+ """
+ invalid_predicates = False
+ if promotion_type == PromotionType.CATALOGUE:
+ if catalogue_predicate is None:
+ errors["catalogue_predicate"].append(
+ ValidationError(
+ message=(
+ "For `catalogue` predicate type, `cataloguePredicate` "
+ "must be provided."
+ ),
+ code=error_class.REQUIRED.value,
+ params={"index": index} if index is not None else {},
+ )
+ )
+ invalid_predicates = True
+ if order_predicate:
+ errors["order_predicate"].append(
+ ValidationError(
+ message=(
+ "`Order` predicate cannot be provided for promotion rule with "
+ "`catalogue` predicate type."
+ ),
+ code=error_class.INVALID.value,
+ params={"index": index} if index is not None else {},
+ )
+ )
+ invalid_predicates = True
+ if promotion_type == PromotionType.ORDER:
+ if order_predicate is None:
+ errors["order_predicate"].append(
+ ValidationError(
+ message=(
+ "For `order` predicate type, `orderPredicate` "
+ "must be provided."
+ ),
+ code=error_class.REQUIRED.value,
+ params={"index": index} if index is not None else {},
+ )
+ )
+ invalid_predicates = True
+ if catalogue_predicate:
+ errors["catalogue_predicate"].append(
+ ValidationError(
+ message=(
+ "`Catalogue` predicate cannot be provided for promotion rule "
+ "with `order` predicate type."
+ ),
+ code=error_class.INVALID.value,
+ params={"index": index} if index is not None else {},
+ )
+ )
+ invalid_predicates = True
+ return invalid_predicates
+
+
+def _clean_catalogue_predicate(
+ cleaned_input, catalogue_predicate, errors, error_class, index, instance
+):
+ """Clean and validate catalogue predicate.
+
+ - Reward type can't be specified for rule with catalogue predicate.
+ """
+
+ if not catalogue_predicate:
+ return
+
+ reward_type = cleaned_input.get("reward_type")
+ if instance and "reward_type" not in cleaned_input:
+ reward_type = reward_type or instance.reward_type
+ if reward_type:
+ errors["reward_type"].append(
ValidationError(
- "The cataloguePredicate field is required.",
- code=error_class.REQUIRED.value,
+ message=(
+ "The rewardType can't be specified for rule "
+ "with cataloguePredicate."
+ ),
+ code=error_class.INVALID.value,
params={"index": index} if index is not None else {},
)
)
else:
- clean_reward(cleaned_input, errors, error_class, index)
-
+ if "catalogue_predicate" not in cleaned_input:
+ return
try:
cleaned_input["catalogue_predicate"] = clean_predicate(
- cleaned_input.get("catalogue_predicate"),
+ catalogue_predicate,
error_class,
index,
)
@@ -32,56 +162,226 @@ def clean_promotion_rule(cleaned_input, errors, error_class, index=None):
errors["catalogue_predicate"].append(error)
-def clean_reward(cleaned_input, errors, error_class, index=None):
+def _clean_order_predicate(
+ cleaned_input,
+ order_predicate,
+ channel_currencies,
+ errors,
+ error_class,
+ index,
+ instance,
+):
+ """Clean and validate order predicate.
+
+ - Reward type is required for rule with order predicate.
+ - Price based predicates are allowed only for rules with one currency.
+ - Rules number with order predicate doesn't exceed the limit.
+ """
+ if not order_predicate:
+ return
+
+ reward_type = cleaned_input.get("reward_type")
+ if "reward_type" not in cleaned_input and instance:
+ reward_type = reward_type or instance.reward_type
+ if not reward_type:
+ errors["reward_type"].append(
+ ValidationError(
+ message="The rewardType is required when orderPredicate is provided.",
+ code=error_class.REQUIRED.value,
+ params={"index": index} if index is not None else {},
+ )
+ )
+ return
+
+ price_based_predicate = any(
+ field in str(order_predicate)
+ for field in [
+ "base_subtotal_price",
+ "baseSubtotalPrice",
+ "base_total_price",
+ "baseTotalPrice",
+ ]
+ )
+ if len(channel_currencies) > 1 and price_based_predicate:
+ error_field = "channels"
+ if instance:
+ error_field = (
+ "add_channels" if "add_channels" in cleaned_input else "order_predicate"
+ )
+ errors[error_field].append(
+ ValidationError(
+ message=(
+ "For price based predicates, all channels must have "
+ "the same currency."
+ ),
+ code=error_class.MULTIPLE_CURRENCIES_NOT_ALLOWED.value,
+ params={"index": index} if index is not None else {},
+ )
+ )
+ return
+
+ if "order_predicate" not in cleaned_input:
+ return
+
+ order_rules_count = PromotionRule.objects.filter(~Q(order_predicate={})).count()
+ rules_limit = settings.ORDER_RULES_LIMIT
+ if order_rules_count >= int(rules_limit):
+ errors["order_predicate"].append(
+ ValidationError(
+ message="Number of rules with orderPredicate has reached the limit.",
+ code=error_class.RULES_NUMBER_LIMIT.value,
+ params={
+ "rules_limit": rules_limit,
+ "exceed_by": 1,
+ },
+ )
+ )
+ return
+
+ try:
+ cleaned_input["order_predicate"] = clean_predicate(
+ order_predicate,
+ error_class,
+ index,
+ )
+ except ValidationError as error:
+ errors["order_predicate"].append(error)
+ return
+
+
+def _clean_reward(
+ cleaned_input,
+ catalogue_predicate,
+ order_predicate,
+ currencies,
+ errors,
+ error_class,
+ index,
+ instance,
+):
+ """Validate reward value and reward value type.
+
+ - Fixed reward value type requires channels with the same currency code
+ to be specified.
+ - Validate price precision for fixed reward value.
+ - Check if percentage reward value is not above 100.
+ """
+ if (
+ instance
+ and "reward_value" not in cleaned_input
+ and "reward_value_type" not in cleaned_input
+ ):
+ return
+
reward_value = cleaned_input.get("reward_value")
reward_value_type = cleaned_input.get("reward_value_type")
- if reward_value_type is None:
+ if instance:
+ reward_value = (
+ reward_value if "reward_value" in cleaned_input else instance.reward_value
+ )
+ reward_value_type = (
+ reward_value_type
+ if "reward_value_type" in cleaned_input
+ else instance.reward_value_type
+ )
+
+ if reward_value_type is None and (catalogue_predicate or order_predicate):
errors["reward_value_type"].append(
ValidationError(
- "The rewardValueType is required for when "
- "cataloguePredicate is provided.",
+ message=(
+ "The rewardValueType is required when "
+ "cataloguePredicate or orderPredicate is provided."
+ ),
code=error_class.REQUIRED.value,
params={"index": index} if index is not None else {},
)
)
- if reward_value is None:
+ if reward_value is None and (catalogue_predicate or order_predicate):
errors["reward_value"].append(
ValidationError(
- "The rewardValue is required when cataloguePredicate is provided.",
+ message=(
+ "The rewardValue is required when "
+ "cataloguePredicate or orderPredicate is provided."
+ ),
code=error_class.REQUIRED.value,
params={"index": index} if index is not None else {},
)
)
if reward_value and reward_value_type:
- clean_reward_value(
+ _clean_reward_value(
+ cleaned_input,
reward_value,
reward_value_type,
- cleaned_input.get("channels"),
+ currencies,
errors,
error_class,
index,
+ instance,
)
-def clean_reward_value(
- reward_value, reward_value_type, channels, errors, error_class, index=None
+def _get_channel_currencies(cleaned_input, instance) -> set[str]:
+ """Get currencies for which the rules apply."""
+ if not instance:
+ channels = cleaned_input.get("channels", [])
+ return {channel.currency_code for channel in channels}
+
+ channel_currencies = set(instance.channels.values_list("currency_code", flat=True))
+ if remove_channels := cleaned_input.get("remove_channels"):
+ channel_currencies = channel_currencies - {
+ channel.currency_code for channel in remove_channels
+ }
+ if add_channels := cleaned_input.get("add_channels"):
+ channel_currencies.update([channel.currency_code for channel in add_channels])
+
+ return channel_currencies
+
+
+def _clean_reward_value(
+ cleaned_input,
+ reward_value,
+ reward_value_type,
+ channel_currencies,
+ errors,
+ error_class,
+ index,
+ instance,
):
+ """Validate reward value and reward value type.
+
+ - The Fixed reward value type requires channels with the same currency code.
+ - Validate price precision for fixed reward value.
+ - Check if percentage reward value is not above 100.
+ """
if reward_value_type == RewardValueType.FIXED:
if "channels" in errors:
return
- if not channels:
- errors["channels"].append(
+ if not channel_currencies:
+ error_field = "channels"
+ if instance:
+ error_field = (
+ "reward_value_type"
+ if "reward_value_type" in cleaned_input
+ else "remove_channels"
+ )
+ errors[error_field].append(
ValidationError(
"Channels must be specified for FIXED rewardValueType.",
- code=error_class.REQUIRED.value,
+ code=error_class.MISSING_CHANNELS.value,
params={"index": index} if index is not None else {},
)
)
return
- currencies = {channel.currency_code for channel in channels}
- if len(currencies) > 1:
+ if len(channel_currencies) > 1:
error_code = error_class.MULTIPLE_CURRENCIES_NOT_ALLOWED.value
- errors["reward_value_type"].append(
+ error_field = "reward_value_type"
+ if instance:
+ error_field = (
+ "reward_value_type"
+ if "reward_value_type" in cleaned_input
+ else "add_channels"
+ )
+ errors[error_field].append(
ValidationError(
"For FIXED rewardValueType, all channels must have "
"the same currency.",
@@ -91,7 +391,7 @@ def clean_reward_value(
)
return
- currency = currencies.pop()
+ currency = channel_currencies.pop()
try:
clean_fixed_discount_value(
reward_value,
diff --git a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
index 0a1996f083..451acca49a 100644
--- a/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
+++ b/saleor/graphql/discount/mutations/sale/sale_base_catalogue.py
@@ -14,7 +14,10 @@ from ....core.mutations import BaseMutation
from ....plugins.dataloaders import get_plugin_manager_promise
from ....product.types import Category, Collection, Product, ProductVariant
from ...types import Sale
-from ...utils import convert_catalogue_info_into_predicate, get_variants_for_predicate
+from ...utils import (
+ convert_catalogue_info_into_predicate,
+ get_variants_for_catalogue_predicate,
+)
from ..utils import update_variants_for_promotion
from ..voucher.voucher_add_catalogues import CatalogueInput
@@ -52,7 +55,7 @@ class SaleBaseCatalogueMutation(BaseMutation):
previous_predicate = convert_catalogue_info_into_predicate(previous_catalogue)
new_predicate = convert_catalogue_info_into_predicate(new_catalogue)
previous_product_ids = cls.get_product_ids_for_predicate(previous_predicate)
- new_variants = get_variants_for_predicate(new_predicate)
+ new_variants = get_variants_for_catalogue_predicate(new_predicate)
new_product_ids = set(
product_models.Product.objects.filter(
Exists(new_variants.filter(product_id=OuterRef("id")))
@@ -70,7 +73,7 @@ class SaleBaseCatalogueMutation(BaseMutation):
@classmethod
def get_product_ids_for_predicate(cls, predicate: dict) -> set[int]:
- variants = get_variants_for_predicate(predicate)
+ variants = get_variants_for_catalogue_predicate(predicate)
products = product_models.Product.objects.filter(
Exists(variants.filter(product_id=OuterRef("id")))
)
diff --git a/saleor/graphql/discount/mutations/sale/sale_create.py b/saleor/graphql/discount/mutations/sale/sale_create.py
index a8082556ea..19a5279df2 100644
--- a/saleor/graphql/discount/mutations/sale/sale_create.py
+++ b/saleor/graphql/discount/mutations/sale/sale_create.py
@@ -5,7 +5,7 @@ import pytz
from django.core.exceptions import ValidationError
from .....core.tracing import traced_atomic_transaction
-from .....discount import models
+from .....discount import PromotionType, models
from .....discount.error_codes import DiscountErrorCode
from .....discount.models import Promotion
from .....permission.enums import DiscountPermissions
@@ -117,16 +117,18 @@ class SaleCreate(ModelMutation):
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
with traced_atomic_transaction():
+ input = data["input"]
+ reward_value_type = input.pop("type", None)
response = super().perform_mutation(_root, info, **data)
promotion: Promotion = response.sale.node
promotion.assign_old_sale_id()
- input = data["input"]
+ promotion.type = PromotionType.CATALOGUE
predicate = cls.create_predicate(input)
models.PromotionRule.objects.create(
name="",
promotion=promotion,
catalogue_predicate=predicate,
- reward_value_type=input.get("type"),
+ reward_value_type=reward_value_type,
)
manager = get_plugin_manager_promise(info.context).get()
cls.send_sale_notifications(manager, promotion, predicate)
diff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.py
index 82c53b9667..76e115008c 100644
--- a/saleor/graphql/discount/mutations/sale/sale_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_update.py
@@ -31,7 +31,7 @@ from ...utils import (
convert_migrated_sale_predicate_to_catalogue_info,
create_catalogue_predicate,
get_products_for_rule,
- get_variants_for_predicate,
+ get_variants_for_catalogue_predicate,
)
from ..utils import update_variants_for_promotion
from .sale_create import SaleInput
@@ -190,7 +190,7 @@ class SaleUpdate(ModelMutation):
field in input.keys()
for field in [*CATALOGUE_FIELDS, "start_date", "end_date", "type"]
):
- variants = get_variants_for_predicate(current_predicate)
+ variants = get_variants_for_catalogue_predicate(current_predicate)
product_ids = set(
product_models.Product.objects.filter(
Exists(variants.filter(product_id=OuterRef("id")))
diff --git a/saleor/graphql/discount/sorters.py b/saleor/graphql/discount/sorters.py
index b9e65714a1..2314ba8046 100644
--- a/saleor/graphql/discount/sorters.py
+++ b/saleor/graphql/discount/sorters.py
@@ -12,7 +12,7 @@ class SaleSortField(BaseEnum):
START_DATE = ["start_date", "name", "pk"]
END_DATE = ["end_date", "name", "pk"]
VALUE = ["value", "name", "pk"]
- TYPE = ["type", "name", "pk"]
+ TYPE = ["value_type", "name", "pk"]
CREATED_AT = ["created_at", "name", "pk"]
LAST_MODIFIED_AT = ["updated_at", "name", "pk"]
@@ -43,7 +43,7 @@ class SaleSortField(BaseEnum):
@staticmethod
def qs_with_type(queryset: QuerySet, **kwargs) -> QuerySet:
- return queryset.annotate(type=F("rules__reward_value_type"))
+ return queryset.annotate(value_type=F("rules__reward_value_type"))
class SaleSortingInput(ChannelSortInputObjectType):
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
index 88c2d94e01..ba17dfd82a 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py
@@ -6,7 +6,7 @@ import pytest
from django.utils import timezone
from ....tests.utils import get_graphql_content
-from ...enums import RewardValueTypeEnum
+from ...enums import PromotionTypeEnum, RewardValueTypeEnum
from ..mutations.test_promotion_create import PROMOTION_CREATE_MUTATION
@@ -65,6 +65,7 @@ def test_promotion_create(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": "Rule 1",
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
index 5ab4be38f4..65cd5cb977 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py
@@ -10,14 +10,14 @@ from ..mutations.test_promotion_delete import PROMOTION_DELETE_MUTATION
def test_promotion_delete(
staff_api_client,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
count_queries,
):
# given
staff_api_client.user.groups.add(permission_group_manage_discounts)
variables = {
- "id": graphene.Node.to_global_id("Promotion", promotion.id),
+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id),
}
# when
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py
index eb2828b1e9..619dccbef8 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py
@@ -16,7 +16,7 @@ def test_promotion_rule_create(
permission_group_manage_discounts,
channel_USD,
channel_PLN,
- promotion,
+ catalogue_promotion,
variant,
product,
category,
@@ -57,7 +57,7 @@ def test_promotion_rule_create(
]
}
- promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ promotion_id = graphene.Node.to_global_id("Promotion", catalogue_promotion.id)
variables = {
"input": {
"promotion": promotion_id,
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_delete.py b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_delete.py
index dd7a279c8e..c38a97829b 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_delete.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_delete.py
@@ -10,12 +10,12 @@ from ..mutations.test_promotion_rule_delete import PROMOTION_RULE_DELETE_MUTATIO
def test_promotion_rule_delete(
staff_api_client,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
count_queries,
):
# given
staff_api_client.user.groups.add(permission_group_manage_discounts)
- rule = promotion.rules.first()
+ rule = catalogue_promotion.rules.first()
variables = {"id": graphene.Node.to_global_id("PromotionRule", rule.id)}
# when
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_update.py b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_update.py
index d31747cdba..6a879affd1 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_update.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_update.py
@@ -16,7 +16,7 @@ def test_promotion_rule_update(
permission_group_manage_discounts,
channel_USD,
channel_PLN,
- promotion,
+ catalogue_promotion,
product_list,
collection,
count_queries,
@@ -24,6 +24,7 @@ def test_promotion_rule_update(
# given
staff_api_client.user.groups.add(permission_group_manage_discounts)
+ promotion = catalogue_promotion
rule = promotion.rules.first()
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_update.py b/saleor/graphql/discount/tests/benchmark/test_promotion_update.py
index bcbc1c9fd2..5b9a85816d 100644
--- a/saleor/graphql/discount/tests/benchmark/test_promotion_update.py
+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_update.py
@@ -14,7 +14,7 @@ def test_promotion_update(
staff_api_client,
description_json,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
count_queries,
):
# given
@@ -23,7 +23,7 @@ def test_promotion_update(
end_date = timezone.now() + timedelta(days=30)
variables = {
- "id": graphene.Node.to_global_id("Promotion", promotion.id),
+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id),
"input": {
"name": "Promotion",
"description": description_json,
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_create.py
index 844912458b..0ec075a6cb 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_create.py
@@ -3,6 +3,7 @@ from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
+from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
@@ -10,7 +11,7 @@ from .....discount import PromotionEvents
from .....discount.error_codes import PromotionCreateErrorCode
from .....discount.models import Promotion, PromotionEvent
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import RewardValueTypeEnum
+from ...enums import PromotionTypeEnum, RewardTypeEnum, RewardValueTypeEnum
PROMOTION_CREATE_MUTATION = """
mutation promotionCreate($input: PromotionCreateInput!) {
@@ -18,6 +19,7 @@ PROMOTION_CREATE_MUTATION = """
promotion {
id
name
+ type
description
startDate
endDate
@@ -34,7 +36,9 @@ PROMOTION_CREATE_MUTATION = """
}
rewardValueType
rewardValue
+ predicateType
cataloguePredicate
+ orderPredicate
}
}
errors {
@@ -42,6 +46,8 @@ PROMOTION_CREATE_MUTATION = """
code
index
message
+ rulesLimit
+ exceedBy
}
}
}
@@ -103,6 +109,7 @@ def test_promotion_create_by_staff_user(
reward_value = Decimal("10")
reward_value_type_1 = RewardValueTypeEnum.FIXED.name
reward_value_type_2 = RewardValueTypeEnum.PERCENTAGE.name
+ promotion_type = PromotionTypeEnum.CATALOGUE.name
variables = {
"input": {
@@ -110,6 +117,7 @@ def test_promotion_create_by_staff_user(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": promotion_type,
"rules": [
{
"name": rule_1_name,
@@ -141,6 +149,7 @@ def test_promotion_create_by_staff_user(
assert not data["errors"]
assert promotion_data["name"] == promotion_name
+ assert promotion_data["type"] == promotion_type
assert promotion_data["description"] == description_json
assert promotion_data["startDate"] == start_date.isoformat()
assert promotion_data["endDate"] == end_date.isoformat()
@@ -149,7 +158,9 @@ def test_promotion_create_by_staff_user(
assert len(promotion_data["rules"]) == 2
for rule_data in variables["input"]["rules"]:
+ rule_data["orderPredicate"] = {}
rule_data["promotion"] = {"id": promotion_data["id"]}
+ rule_data["predicateType"] = promotion_type
rule_data["channels"] = [
{"id": channel_id} for channel_id in rule_data["channels"]
]
@@ -278,6 +289,7 @@ def test_promotion_create_by_customer(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": "test promotion rule",
@@ -302,6 +314,69 @@ def test_promotion_create_by_customer(
update_products_discounted_prices_of_promotion_task_mock.assert_not_called()
+@freeze_time("2020-03-18 12:00:00")
+def test_promotion_create_with_order_rule(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ channel_PLN,
+ product,
+):
+ # given
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ start_date = timezone.now() - timedelta(days=30)
+ end_date = timezone.now() + timedelta(days=30)
+
+ promotion_name = "test promotion"
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ rule_name = "test promotion rule 1"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.FIXED.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
+
+ variables = {
+ "input": {
+ "name": promotion_name,
+ "description": description_json,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.ORDER.name,
+ "rules": [
+ {
+ "name": rule_name,
+ "description": description_json,
+ "channels": channel_ids,
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "orderPredicate": order_predicate,
+ }
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionCreate"]
+ promotion_data = data["promotion"]
+
+ assert not data["errors"]
+ assert promotion_data["name"] == promotion_name
+ assert promotion_data["description"] == description_json
+ assert promotion_data["startDate"] == start_date.isoformat()
+ assert promotion_data["endDate"] == end_date.isoformat()
+
+ promotion = Promotion.objects.filter(name=promotion_name).get()
+ assert promotion.last_notification_scheduled_at == timezone.now()
+
+
def test_promotion_create_fixed_reward_value_multiple_currencies(
staff_api_client,
permission_manage_discounts,
@@ -340,6 +415,7 @@ def test_promotion_create_fixed_reward_value_multiple_currencies(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": "test promotion rule",
@@ -408,6 +484,7 @@ def test_promotion_create_invalid_price_precision(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": "test promotion rule",
@@ -476,6 +553,7 @@ def test_promotion_create_invalid_percentage_value(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": "test promotion rule",
@@ -611,6 +689,7 @@ def test_promotion_create_start_date_and_end_date_after_current_date(
reward_value = Decimal("10")
reward_value_type_1 = RewardValueTypeEnum.FIXED.name
reward_value_type_2 = RewardValueTypeEnum.PERCENTAGE.name
+ promotion_type = PromotionTypeEnum.CATALOGUE.name
variables = {
"input": {
@@ -618,6 +697,7 @@ def test_promotion_create_start_date_and_end_date_after_current_date(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": promotion_type,
"rules": [
{
"name": rule_1_name,
@@ -649,6 +729,7 @@ def test_promotion_create_start_date_and_end_date_after_current_date(
assert not data["errors"]
assert promotion_data["name"] == promotion_name
+ assert promotion_data["type"] == promotion_type
assert promotion_data["description"] == description_json
assert promotion_data["startDate"] == start_date.isoformat()
assert promotion_data["endDate"] == end_date.isoformat()
@@ -657,7 +738,9 @@ def test_promotion_create_start_date_and_end_date_after_current_date(
assert len(promotion_data["rules"]) == 2
for rule_data in variables["input"]["rules"]:
+ rule_data["orderPredicate"] = {}
rule_data["promotion"] = {"id": promotion_data["id"]}
+ rule_data["predicateType"] = promotion_type
rule_data["channels"] = [
{"id": channel_id} for channel_id in rule_data["channels"]
]
@@ -674,7 +757,7 @@ def test_promotion_create_start_date_and_end_date_after_current_date(
@freeze_time("2020-03-18 12:00:00")
-def test_promotion_create_missing_catalogue_predicate(
+def test_promotion_create_missing_predicate(
staff_api_client,
permission_group_manage_discounts,
description_json,
@@ -706,6 +789,7 @@ def test_promotion_create_missing_catalogue_predicate(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": rule_1_name,
@@ -736,9 +820,14 @@ def test_promotion_create_missing_catalogue_predicate(
assert not data["promotion"]
assert len(errors) == 1
- assert errors[0]["code"] == PromotionCreateErrorCode.REQUIRED.name
- assert errors[0]["field"] == "cataloguePredicate"
- assert errors[0]["index"] == 1
+ assert {
+ "code": PromotionCreateErrorCode.REQUIRED.name,
+ "field": "cataloguePredicate",
+ "index": 1,
+ "message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
+ } in errors
@freeze_time("2020-03-18 12:00:00")
@@ -774,6 +863,7 @@ def test_promotion_create_missing_reward_value(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": rule_1_name,
@@ -840,6 +930,7 @@ def test_promotion_create_missing_reward_value_type(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": rule_1_name,
@@ -868,22 +959,12 @@ def test_promotion_create_missing_reward_value_type(
assert not data["promotion"]
assert len(errors) == 2
- expected_errors = [
- {
- "code": PromotionCreateErrorCode.REQUIRED.name,
- "field": "rewardValueType",
- "index": 0,
- "message": ANY,
- },
- {
- "code": PromotionCreateErrorCode.REQUIRED.name,
- "field": "rewardValueType",
- "index": 1,
- "message": ANY,
- },
- ]
- for error in expected_errors:
- assert error in errors
+ error_fields = set([error["field"] for error in errors])
+ assert len(error_fields) == 1
+ assert "rewardValueType" in error_fields
+ error_codes = set([error["code"] for error in errors])
+ assert len(error_codes) == 1
+ assert PromotionCreateErrorCode.REQUIRED.name in error_codes
@freeze_time("2020-03-18 12:00:00")
@@ -919,6 +1000,7 @@ def test_promotion_create_invalid_channel_id(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": rule_1_name,
@@ -955,6 +1037,159 @@ def test_promotion_create_invalid_channel_id(
assert errors[0]["index"] == 0
+def test_promotion_create_mixed_catalogue_and_order_rules(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ channel_PLN,
+ variant,
+ product,
+ collection,
+ category,
+):
+ # given
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ start_date = timezone.now() - timedelta(days=30)
+ end_date = timezone.now() + timedelta(days=30)
+
+ rule_1_channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
+ rule_2_channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
+ promotion_name = "test promotion"
+ catalogue_predicate = {
+ "productPredicate": {"ids": [graphene.Node.to_global_id("Product", product.id)]}
+ }
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ rule_1_name = "test promotion rule 1"
+ rule_2_name = "test promotion rule 2"
+ reward_value = Decimal("10")
+ reward_value_type_1 = RewardValueTypeEnum.FIXED.name
+ reward_value_type_2 = RewardValueTypeEnum.PERCENTAGE.name
+
+ variables = {
+ "input": {
+ "name": promotion_name,
+ "description": description_json,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
+ "rules": [
+ {
+ "name": rule_1_name,
+ "description": description_json,
+ "channels": rule_1_channel_ids,
+ "rewardValueType": reward_value_type_1,
+ "rewardValue": reward_value,
+ "cataloguePredicate": catalogue_predicate,
+ },
+ {
+ "name": rule_2_name,
+ "description": description_json,
+ "channels": rule_2_channel_ids,
+ "rewardValueType": reward_value_type_2,
+ "rewardValue": reward_value,
+ "orderPredicate": order_predicate,
+ },
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionCreate"]
+ errors = data["errors"]
+
+ assert not data["promotion"]
+ assert len(errors) == 2
+ assert {
+ "code": PromotionCreateErrorCode.REQUIRED.name,
+ "field": "cataloguePredicate",
+ "index": 1,
+ "rulesLimit": None,
+ "exceedBy": None,
+ "message": ANY,
+ } in errors
+ assert {
+ "code": PromotionCreateErrorCode.INVALID.name,
+ "field": "orderPredicate",
+ "index": 1,
+ "rulesLimit": None,
+ "exceedBy": None,
+ "message": ANY,
+ } in errors
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_promotion_create_mixed_currencies_for_price_based_predicate(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ channel_PLN,
+ product,
+):
+ # given
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ start_date = timezone.now() - timedelta(days=30)
+ end_date = timezone.now() + timedelta(days=30)
+
+ promotion_name = "test promotion"
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ rule_name = "test promotion rule 1"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ channel_ids = [
+ graphene.Node.to_global_id("Channel", channel.pk)
+ for channel in [channel_USD, channel_PLN]
+ ]
+
+ variables = {
+ "input": {
+ "name": promotion_name,
+ "description": description_json,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.ORDER.name,
+ "rules": [
+ {
+ "name": rule_name,
+ "description": description_json,
+ "channels": channel_ids,
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "orderPredicate": order_predicate,
+ },
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionCreate"]
+ errors = data["errors"]
+
+ assert not data["promotion"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == PromotionCreateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.name
+ )
+ assert errors[0]["field"] == "channels"
+ assert errors[0]["index"] == 0
+
+
@freeze_time("2020-03-18 12:00:00")
def test_promotion_create_multiple_errors(
staff_api_client,
@@ -979,6 +1214,7 @@ def test_promotion_create_multiple_errors(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": "test promotion rule 1",
@@ -1006,18 +1242,24 @@ def test_promotion_create_multiple_errors(
"field": "rewardValue",
"index": 0,
"message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
},
{
"code": PromotionCreateErrorCode.REQUIRED.name,
"field": "rewardValueType",
"index": 0,
"message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
},
{
"code": PromotionCreateErrorCode.GRAPHQL_ERROR.name,
"field": "channels",
"index": 0,
"message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
},
]
for error in expected_errors:
@@ -1057,6 +1299,7 @@ def test_promotion_create_end_date_before_start_date(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": rule_1_name,
@@ -1148,6 +1391,7 @@ def test_promotion_create_invalid_catalogue_predicate(
"description": description_json,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"name": rule_1_name,
@@ -1184,6 +1428,64 @@ def test_promotion_create_invalid_catalogue_predicate(
assert errors[0]["index"] == 1
+@override_settings(ORDER_RULES_LIMIT=1)
+def test_promotion_create_exceeds_rules_number_limit(
+ staff_api_client,
+ permission_group_manage_discounts,
+ channel_USD,
+ product,
+ order_promotion_with_rule,
+):
+ # given
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ start_date = timezone.now() - timedelta(days=30)
+ end_date = timezone.now() + timedelta(days=30)
+
+ promotion_name = "test promotion"
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ rule_name = "test promotion rule 1"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+
+ variables = {
+ "input": {
+ "name": promotion_name,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "type": PromotionTypeEnum.ORDER.name,
+ "rules": [
+ {
+ "name": rule_name,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "orderPredicate": order_predicate,
+ }
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionCreate"]
+ errors = data["errors"]
+
+ assert not data["promotion"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionCreateErrorCode.RULES_NUMBER_LIMIT.name
+ assert errors[0]["field"] == "rules"
+ assert errors[0]["rulesLimit"] == 1
+ assert errors[0]["exceedBy"] == 1
+
+
@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.promotion_started")
@patch("saleor.plugins.manager.PluginsManager.promotion_created")
@@ -1199,6 +1501,7 @@ def test_promotion_create_rules_without_channels_and_percentage_reward(
permission_group_manage_discounts.user_set.add(staff_api_client.user)
start_date = timezone.now() - timedelta(days=30)
end_date = timezone.now() + timedelta(days=30)
+
catalogue_predicate = {
"variantPredicate": {
"ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
@@ -1226,6 +1529,7 @@ def test_promotion_create_rules_without_channels_and_percentage_reward(
# then
content = get_graphql_content(response)
data = content["data"]["promotionCreate"]
+
assert not data["errors"]
assert data["promotion"]["rules"]
@@ -1290,6 +1594,7 @@ def test_promotion_create_events_by_staff_user(
variables = {
"input": {
"name": "test promotion",
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"channels": rule_1_channel_ids,
@@ -1362,6 +1667,7 @@ def test_promotion_create_events_by_app(
variables = {
"input": {
"name": "test promotion",
+ "type": PromotionTypeEnum.CATALOGUE.name,
"rules": [
{
"channels": rule_1_channel_ids,
@@ -1454,7 +1760,11 @@ def test_promotion_create_without_catalogue_predicate(
# then
content = get_graphql_content(response)
data = content["data"]["promotionCreate"]
- assert not data["errors"]
- assert data["promotion"]
- assert len(data["promotion"]["rules"]) == 1
- assert data["promotion"]["rules"][0]["cataloguePredicate"] == {}
+ assert not data["promotion"]
+ assert data["errors"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["code"] == PromotionCreateErrorCode.REQUIRED.name
+ assert error["field"] == "cataloguePredicate"
+ assert error["rulesLimit"] is None
+ assert error["exceedBy"] is None
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py b/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
index e64f81f4dc..f318494f43 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_delete.py
@@ -29,10 +29,11 @@ def test_promotion_delete_by_staff_user(
update_discounted_prices_task_mock,
staff_api_client,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ promotion = catalogue_promotion
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}
# when
@@ -58,9 +59,10 @@ def test_promotion_delete_by_staff_app(
update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}
# when
@@ -86,10 +88,10 @@ def test_promotion_delete_by_customer(
promotion_deleted_mock,
update_discounted_prices_task_mock,
api_client,
- promotion,
+ catalogue_promotion,
):
# given
- variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}
+ variables = {"id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id)}
# when
response = api_client.post_graphql(PROMOTION_DELETE_MUTATION, variables)
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
index 230f10b0a8..4b8b8a9d04 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py
@@ -2,12 +2,13 @@ from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
+from django.test import override_settings
from .....discount import PromotionEvents
from .....discount.error_codes import PromotionRuleCreateErrorCode
from .....discount.models import PromotionEvent
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import RewardValueTypeEnum
+from ...enums import RewardTypeEnum, RewardValueTypeEnum
PROMOTION_RULE_CREATE_MUTATION = """
mutation promotionRuleCreate($input: PromotionRuleCreateInput!) {
@@ -32,12 +33,16 @@ PROMOTION_RULE_CREATE_MUTATION = """
}
rewardValueType
rewardValue
+ predicateType
cataloguePredicate
+ orderPredicate
}
errors {
field
code
message
+ rulesLimit
+ exceedBy
}
}
}
@@ -58,10 +63,11 @@ def test_promotion_rule_create_by_staff_user(
product,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ promotion = catalogue_promotion
channel_ids = [
graphene.Node.to_global_id("Channel", channel.pk)
@@ -121,6 +127,7 @@ def test_promotion_rule_create_by_staff_user(
assert rule_data["name"] == name
assert rule_data["description"] == description_json
assert {channel["id"] for channel in rule_data["channels"]} == set(channel_ids)
+ assert rule_data["predicateType"] == promotion.type.upper()
assert rule_data["cataloguePredicate"] == catalogue_predicate
assert rule_data["rewardValueType"] == reward_value_type
assert rule_data["rewardValue"] == reward_value
@@ -140,9 +147,10 @@ def test_promotion_rule_create_by_app(
channel_PLN,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
catalogue_predicate = {
"OR": [
@@ -192,6 +200,7 @@ def test_promotion_rule_create_by_app(
assert rule_data["name"] == name
assert rule_data["description"] == description_json
assert {channel["id"] for channel in rule_data["channels"]} == set(channel_ids)
+ assert rule_data["predicateType"] == promotion.type.upper()
assert rule_data["cataloguePredicate"] == catalogue_predicate
assert rule_data["rewardValueType"] == reward_value_type
assert rule_data["rewardValue"] == reward_value
@@ -210,9 +219,10 @@ def test_promotion_rule_create_by_customer(
channel_USD,
category,
collection,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
catalogue_predicate = {
"OR": [
@@ -251,17 +261,18 @@ def test_promotion_rule_create_by_customer(
update_discounted_prices_task_mock.assert_not_called()
-def test_promotion_rule_create_missing_catalogue_predicate(
+def test_promotion_rule_create_missing_predicate(
staff_api_client,
permission_group_manage_discounts,
description_json,
channel_USD,
channel_PLN,
product,
- promotion,
+ order_promotion_with_rule,
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ promotion = order_promotion_with_rule
channel_ids = [
graphene.Node.to_global_id("Channel", channel.pk)
@@ -294,8 +305,13 @@ def test_promotion_rule_create_missing_catalogue_predicate(
assert not data["promotionRule"]
assert len(errors) == 1
- assert errors[0]["code"] == PromotionRuleCreateErrorCode.REQUIRED.name
- assert errors[0]["field"] == "cataloguePredicate"
+ assert {
+ "code": PromotionRuleCreateErrorCode.REQUIRED.name,
+ "field": "orderPredicate",
+ "message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
+ } in errors
assert promotion.rules.count() == rules_count
@@ -306,9 +322,10 @@ def test_promotion_rule_create_missing_reward_value(
channel_USD,
channel_PLN,
product,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [
@@ -356,9 +373,10 @@ def test_promotion_rule_create_missing_reward_value_type(
channel_USD,
channel_PLN,
product,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [
@@ -406,9 +424,10 @@ def test_promotion_rule_create_multiple_errors(
channel_USD,
channel_PLN,
product,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [
@@ -446,11 +465,15 @@ def test_promotion_rule_create_multiple_errors(
"code": PromotionRuleCreateErrorCode.REQUIRED.name,
"field": "rewardValue",
"message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
},
{
"code": PromotionRuleCreateErrorCode.REQUIRED.name,
"field": "rewardValueType",
"message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
},
]
for error in expected_errors:
@@ -468,9 +491,10 @@ def test_promotion_rule_invalid_catalogue_predicate(
variant,
product,
collection,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [
@@ -526,6 +550,68 @@ def test_promotion_rule_invalid_catalogue_predicate(
assert promotion.rules.count() == rules_count
+def test_promotion_rule_invalid_order_predicate(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_PLN,
+ order_promotion_without_rules,
+):
+ # given
+ promotion = order_promotion_without_rules
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+
+ channel_ids = [graphene.Node.to_global_id("Channel", channel_PLN.pk)]
+ order_predicate = {
+ "OR": [
+ {
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"range": {"gte": 100}}
+ },
+ "AND": [
+ {
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"range": {"lte": 500}}
+ }
+ }
+ ],
+ }
+ ]
+ }
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": channel_ids,
+ "rewardValueType": reward_value_type,
+ "rewardType": RewardTypeEnum.SUBTOTAL_DISCOUNT.name,
+ "rewardValue": reward_value,
+ "orderPredicate": order_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.INVALID.name
+ assert errors[0]["field"] == "orderPredicate"
+ assert promotion.rules.count() == rules_count
+
+
def test_promotion_rule_create_invalid_price_precision(
staff_api_client,
permission_group_manage_discounts,
@@ -533,9 +619,10 @@ def test_promotion_rule_create_invalid_price_precision(
channel_USD,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
@@ -594,9 +681,10 @@ def test_promotion_rule_create_fixed_reward_value_multiple_currencies(
channel_PLN,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [
@@ -659,9 +747,10 @@ def test_promotion_rule_create_fixed_reward_no_channels(
description_json,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
catalogue_predicate = {
@@ -706,7 +795,7 @@ def test_promotion_rule_create_fixed_reward_no_channels(
assert not data["promotionRule"]
assert len(errors) == 1
- assert errors[0]["code"] == PromotionRuleCreateErrorCode.REQUIRED.name
+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.MISSING_CHANNELS.name
assert errors[0]["field"] == "channels"
assert promotion.rules.count() == rules_count
@@ -719,9 +808,10 @@ def test_promotion_rule_create_percentage_value_above_100(
channel_PLN,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [
@@ -835,6 +925,7 @@ def test_promotion_rule_create_clears_old_sale_id(
assert rule_data["name"] == name
assert rule_data["description"] == description_json
assert {channel["id"] for channel in rule_data["channels"]} == set(channel_ids)
+ assert rule_data["predicateType"] == promotion.type.upper()
assert rule_data["cataloguePredicate"] == catalogue_predicate
assert rule_data["rewardValueType"] == reward_value_type
assert rule_data["rewardValue"] == reward_value
@@ -851,9 +942,10 @@ def test_promotion_rule_create_events(
permission_group_manage_discounts,
channel_USD,
variant,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]
catalogue_predicate = {
@@ -904,9 +996,10 @@ def test_promotion_rule_create_serializable_decimal_in_predicate(
promotion_rule_created_mock,
staff_api_client,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
catalogue_predicate = {
"productPredicate": {"minimalPrice": {"range": {"gte": "25"}}}
@@ -934,6 +1027,447 @@ def test_promotion_rule_create_serializable_decimal_in_predicate(
assert data["promotionRule"]["cataloguePredicate"] == catalogue_predicate
+def test_promotion_rule_create_multiple_predicates(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ product,
+ catalogue_promotion,
+):
+ # given
+ promotion = catalogue_promotion
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.FIXED.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ catalogue_predicate = {
+ "productPredicate": {"ids": [graphene.Node.to_global_id("Product", product.id)]}
+ }
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "cataloguePredicate": catalogue_predicate,
+ "orderPredicate": order_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert {
+ "code": PromotionRuleCreateErrorCode.INVALID.name,
+ "field": "orderPredicate",
+ "message": ANY,
+ "rulesLimit": None,
+ "exceedBy": None,
+ } in errors
+ assert promotion.rules.count() == rules_count
+
+
+def test_promotion_rule_create_mixed_predicates_order(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ product,
+ catalogue_promotion,
+):
+ # given
+ promotion = catalogue_promotion
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.FIXED.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ catalogue_predicate = {
+ "productPredicate": {"ids": [graphene.Node.to_global_id("Product", product.id)]}
+ }
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "orderPredicate": order_predicate,
+ "cataloguePredicate": catalogue_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.INVALID.name
+ assert errors[0]["field"] == "orderPredicate"
+ assert promotion.rules.count() == rules_count
+
+
+def test_promotion_rule_create_mixed_predicates_catalogue(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ product,
+ order_promotion_without_rules,
+):
+ # given
+ promotion = order_promotion_without_rules
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.FIXED.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ catalogue_predicate = {
+ "productPredicate": {"ids": [graphene.Node.to_global_id("Product", product.id)]}
+ }
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}
+ }
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "orderPredicate": order_predicate,
+ "cataloguePredicate": catalogue_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.INVALID.name
+ assert errors[0]["field"] == "cataloguePredicate"
+ assert promotion.rules.count() == rules_count
+
+
+def test_promotion_rule_create_missing_reward_type(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ product,
+ order_promotion_without_rules,
+):
+ # given
+ promotion = order_promotion_without_rules
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.FIXED.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "orderPredicate": order_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "rewardType"
+ assert promotion.rules.count() == rules_count
+
+
+def test_promotion_rule_create_reward_type_with_catalogue_predicate(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ product,
+ catalogue_promotion,
+):
+ # given
+ promotion = catalogue_promotion
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.FIXED.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ catalogue_predicate = {
+ "productPredicate": {"ids": [graphene.Node.to_global_id("Product", product.id)]}
+ }
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "cataloguePredicate": catalogue_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.INVALID.name
+ assert errors[0]["field"] == "rewardType"
+ assert promotion.rules.count() == rules_count
+
+
+@patch("saleor.plugins.manager.PluginsManager.promotion_rule_created")
+@patch(
+ "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
+)
+def test_promotion_rule_create_order_predicate(
+ update_products_discounted_prices_for_promotion_task_mock,
+ promotion_rule_created_mock,
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ order_promotion_without_rules,
+):
+ # given
+ promotion = order_promotion_without_rules
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}
+ }
+
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "orderPredicate": order_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ rule_data = data["promotionRule"]
+
+ assert not data["errors"]
+ assert rule_data["name"] == name
+ assert rule_data["description"] == description_json
+ assert rule_data["channels"][0]["id"] == channel_id
+ assert rule_data["orderPredicate"] == order_predicate
+ assert rule_data["predicateType"] == promotion.type.upper()
+ assert rule_data["rewardValueType"] == reward_value_type
+ assert rule_data["rewardValue"] == reward_value
+ assert rule_data["promotion"]["id"] == promotion_id
+ assert promotion.rules.count() == rules_count + 1
+ rule = promotion.rules.last()
+ promotion_rule_created_mock.assert_called_once_with(rule)
+
+
+def test_promotion_rule_create_mixed_currencies_for_price_based_predicate(
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ channel_USD,
+ channel_PLN,
+ order_promotion_without_rules,
+):
+ # given
+ promotion = order_promotion_without_rules
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+ name = "test promotion rule"
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}
+ }
+ channel_ids = [
+ graphene.Node.to_global_id("Channel", channel.pk)
+ for channel in [channel_USD, channel_PLN]
+ ]
+
+ rules_count = promotion.rules.count()
+
+ variables = {
+ "input": {
+ "name": name,
+ "promotion": promotion_id,
+ "description": description_json,
+ "channels": channel_ids,
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "orderPredicate": order_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == PromotionRuleCreateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.name
+ )
+ assert errors[0]["field"] == "channels"
+ assert promotion.rules.count() == rules_count
+
+
+@override_settings(ORDER_RULES_LIMIT=1)
+def test_promotion_rule_create_exceeds_rules_number_limit(
+ staff_api_client,
+ permission_group_manage_discounts,
+ channel_USD,
+ order_promotion_without_rules,
+):
+ # given
+ promotion = order_promotion_without_rules
+ permission_group_manage_discounts.user_set.add(staff_api_client.user)
+
+ reward_value = Decimal("10")
+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}
+ }
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+
+ promotion.rules.create(
+ name="existing promotion rule",
+ promotion=promotion,
+ order_predicate=order_predicate,
+ reward_value_type=reward_value_type,
+ reward_value=reward_value,
+ reward_type=reward_type,
+ )
+
+ rules_count = promotion.rules.count()
+ assert rules_count == 1
+
+ variables = {
+ "input": {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "rewardValueType": reward_value_type,
+ "rewardValue": reward_value,
+ "rewardType": reward_type,
+ "orderPredicate": order_predicate,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleCreate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.RULES_NUMBER_LIMIT.name
+ assert errors[0]["field"] == "orderPredicate"
+ assert errors[0]["rulesLimit"] == 1
+ assert errors[0]["exceedBy"] == 1
+ assert promotion.rules.count() == rules_count
+
+
def test_promotion_rule_create_with_metadata(
staff_api_client,
permission_group_manage_discounts,
@@ -944,7 +1478,7 @@ def test_promotion_rule_create_with_metadata(
product,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
@@ -959,7 +1493,7 @@ def test_promotion_rule_create_with_metadata(
name = "test promotion rule"
reward_value = Decimal("10")
reward_value_type = RewardValueTypeEnum.PERCENTAGE.name
- promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ promotion_id = graphene.Node.to_global_id("Promotion", catalogue_promotion.id)
variables = {
"input": {
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
index 8b051b05e2..bcf82218bc 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_delete.py
@@ -41,12 +41,12 @@ def test_promotion_rule_delete_by_staff_user(
promotion_rule_deleted_mock,
staff_api_client,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
product,
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- rule = promotion.rules.get(name="Percentage promotion rule")
+ rule = catalogue_promotion.rules.get(name="Percentage promotion rule")
variables = {"id": graphene.Node.to_global_id("PromotionRule", rule.id)}
# when
@@ -68,11 +68,11 @@ def test_promotion_rule_delete_by_staff_app(
update_discounted_prices_task_mock,
app_api_client,
permission_manage_discounts,
- promotion,
+ catalogue_promotion,
product,
):
# given
- rule = promotion.rules.get(name="Percentage promotion rule")
+ rule = catalogue_promotion.rules.get(name="Percentage promotion rule")
variables = {"id": graphene.Node.to_global_id("PromotionRule", rule.id)}
# when
@@ -94,10 +94,10 @@ def test_promotion_rule_delete_by_staff_app(
@patch("saleor.product.tasks.update_discounted_prices_task.delay")
def test_promotion_rule_delete_by_customer(
- update_discounted_prices_task_mock, api_client, promotion
+ update_discounted_prices_task_mock, api_client, catalogue_promotion
):
# given
- rule = promotion.rules.first()
+ rule = catalogue_promotion.rules.first()
variables = {"id": graphene.Node.to_global_id("PromotionRule", rule.id)}
# when
@@ -142,11 +142,11 @@ def test_promotion_delete_clears_old_sale_id(
def test_promotion_rule_delete_events(
- staff_api_client, permission_group_manage_discounts, promotion
+ staff_api_client, permission_group_manage_discounts, catalogue_promotion
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
- rule = promotion.rules.first()
+ rule = catalogue_promotion.rules.first()
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
variables = {"id": rule_id}
event_count = PromotionEvent.objects.count()
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
index 634f142db2..dbbf0d4a70 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py
@@ -7,7 +7,7 @@ from .....discount import PromotionEvents, RewardValueType
from .....discount.error_codes import PromotionRuleUpdateErrorCode
from .....discount.models import PromotionEvent
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import RewardValueTypeEnum
+from ...enums import RewardTypeEnum, RewardValueTypeEnum
PROMOTION_RULE_UPDATE_MUTATION = """
mutation promotionRuleUpdate($id: ID!, $input: PromotionRuleUpdateInput!) {
@@ -31,6 +31,7 @@ PROMOTION_RULE_UPDATE_MUTATION = """
}
rewardValueType
rewardValue
+ rewardType
cataloguePredicate
}
errors {
@@ -55,10 +56,11 @@ def test_promotion_rule_update_by_staff_user(
channel_PLN,
collection,
category,
- promotion,
+ catalogue_promotion,
product_list,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
rule = promotion.rules.create(
name="Rule",
@@ -142,10 +144,11 @@ def test_promotion_rule_update_by_app(
permission_manage_discounts,
channel_USD,
channel_PLN,
- promotion,
+ catalogue_promotion,
product,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Percentage promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -197,9 +200,10 @@ def test_promotion_rule_update_by_customer(
api_client,
channel_USD,
channel_PLN,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.first()
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -233,9 +237,10 @@ def test_promotion_rule_update_duplicates_channels_in_add_and_remove_field(
channel_PLN,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
rule = promotion.rules.first()
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -308,9 +313,10 @@ def test_promotion_rule_update_invalid_catalogue_predicate(
channel_PLN,
collection,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
rule = promotion.rules.first()
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -359,9 +365,10 @@ def test_promotion_rule_update_add_channel_with_different_currency_to_fixed_disc
app_api_client,
permission_manage_discounts,
channel_PLN,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Fixed promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -401,9 +408,10 @@ def test_promotion_rule_update_remove_last_channel_from_fixed_discount(
app_api_client,
permission_manage_discounts,
channel_USD,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Fixed promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -441,9 +449,10 @@ def test_promotion_rule_update_remove_and_add_channel_with_the_same_currency(
permission_manage_discounts,
channel_USD,
other_channel_USD,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Fixed promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -479,9 +488,10 @@ def test_promotion_rule_update_change_reward_value_type_to_fixed_multiple_channe
app_api_client,
permission_manage_discounts,
channel_PLN,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Percentage promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -520,9 +530,10 @@ def test_promotion_rule_update_change_reward_value_type_to_fixed_multiple_channe
def test_promotion_rule_update_change_reward_value_type_to_fixed_no_channels(
app_api_client,
permission_manage_discounts,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Percentage promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -560,9 +571,10 @@ def test_promotion_rule_update_reward_value_invalid_precision(
permission_manage_discounts,
channel_USD,
channel_PLN,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Fixed promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -602,9 +614,10 @@ def test_promotion_rule_update_reward_value_invalid_percentage_value(
permission_manage_discounts,
channel_USD,
channel_PLN,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
rule = promotion.rules.get(name="Percentage promotion rule")
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -737,9 +750,10 @@ def test_promotion_rule_update_events(
permission_group_manage_discounts,
channel_PLN,
category,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
rule = promotion.rules.first()
rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
@@ -782,3 +796,235 @@ def test_promotion_rule_update_events(
assert PromotionEvents.RULE_UPDATED.upper() == events[0]["type"]
assert events[0]["ruleId"] == rule_id
+
+
+def test_promotion_rule_update_mix_predicates_invalid_order_predicate(
+ app_api_client,
+ permission_manage_discounts,
+ catalogue_promotion,
+):
+ # given
+ promotion = catalogue_promotion
+ rule = promotion.rules.get(name="Percentage promotion rule")
+ assert rule.catalogue_predicate
+ assert not rule.order_predicate
+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
+
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+
+ variables = {
+ "id": rule_id,
+ "input": {"orderPredicate": order_predicate},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PROMOTION_RULE_UPDATE_MUTATION,
+ variables,
+ permissions=(permission_manage_discounts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleUpdate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.INVALID.name
+ assert errors[0]["field"] == "orderPredicate"
+
+
+def test_promotion_rule_update_mix_predicates_invalid_catalogue_predicate(
+ app_api_client,
+ permission_manage_discounts,
+ order_promotion_with_rule,
+ product,
+):
+ # given
+ promotion = order_promotion_with_rule
+ rule = promotion.rules.first()
+ assert not rule.catalogue_predicate
+ assert rule.order_predicate
+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
+
+ catalogue_predicate = {
+ "productPredicate": {"ids": [graphene.Node.to_global_id("Product", product.id)]}
+ }
+
+ variables = {
+ "id": rule_id,
+ "input": {"cataloguePredicate": catalogue_predicate},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PROMOTION_RULE_UPDATE_MUTATION,
+ variables,
+ permissions=(permission_manage_discounts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleUpdate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.INVALID.name
+ assert errors[0]["field"] == "cataloguePredicate"
+
+
+def test_promotion_rule_update_mix_predicates_both_predicate_types_given(
+ app_api_client,
+ product,
+ permission_manage_discounts,
+ catalogue_promotion,
+):
+ # given
+ promotion = catalogue_promotion
+ rule = promotion.rules.get(name="Percentage promotion rule")
+ assert rule.catalogue_predicate
+ assert not rule.order_predicate
+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
+
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ catalogue_predicate = {
+ "productPredicate": {"ids": [graphene.Node.to_global_id("Product", product.id)]}
+ }
+
+ variables = {
+ "id": rule_id,
+ "input": {
+ "orderPredicate": order_predicate,
+ "cataloguePredicate": catalogue_predicate,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PROMOTION_RULE_UPDATE_MUTATION,
+ variables,
+ permissions=(permission_manage_discounts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleUpdate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert {
+ "code": PromotionRuleUpdateErrorCode.INVALID.name,
+ "field": "orderPredicate",
+ "message": ANY,
+ "channels": None,
+ } in errors
+
+
+def test_promotion_rule_update_reward_type_with_catalogue_predicate(
+ app_api_client,
+ permission_manage_discounts,
+ catalogue_promotion,
+):
+ # given
+ promotion = catalogue_promotion
+ rule = promotion.rules.get(name="Percentage promotion rule")
+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
+ reward_type = RewardTypeEnum.SUBTOTAL_DISCOUNT.name
+
+ variables = {
+ "id": rule_id,
+ "input": {"rewardType": reward_type},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PROMOTION_RULE_UPDATE_MUTATION,
+ variables,
+ permissions=(permission_manage_discounts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleUpdate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.INVALID.name
+ assert errors[0]["field"] == "rewardType"
+
+
+def test_promotion_rule_update_clear_reward_type_for_order_predicate(
+ app_api_client,
+ permission_manage_discounts,
+ order_promotion_with_rule,
+):
+ # given
+ promotion = order_promotion_with_rule
+ rule = promotion.rules.first()
+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
+ variables = {
+ "id": rule_id,
+ "input": {"rewardType": None},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PROMOTION_RULE_UPDATE_MUTATION,
+ variables,
+ permissions=(permission_manage_discounts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleUpdate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "rewardType"
+
+
+def test_promotion_rule_update_add_invalid_channels_for_order_rule(
+ app_api_client,
+ permission_manage_discounts,
+ order_promotion_with_rule,
+ channel_PLN,
+):
+ # given
+ promotion = order_promotion_with_rule
+ rule = promotion.rules.first()
+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variables = {
+ "id": rule_id,
+ "input": {"addChannels": [channel_id]},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PROMOTION_RULE_UPDATE_MUTATION,
+ variables,
+ permissions=(permission_manage_discounts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["promotionRuleUpdate"]
+ errors = data["errors"]
+
+ assert not data["promotionRule"]
+ assert len(errors) == 1
+ assert (
+ errors[0]["code"]
+ == PromotionRuleUpdateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.name
+ )
+ assert errors[0]["field"] == "addChannels"
diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_update.py b/saleor/graphql/discount/tests/mutations/test_promotion_update.py
index eff74bb388..d1b7f1c9f5 100644
--- a/saleor/graphql/discount/tests/mutations/test_promotion_update.py
+++ b/saleor/graphql/discount/tests/mutations/test_promotion_update.py
@@ -47,9 +47,10 @@ def test_promotion_update_by_staff_user(
update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
start_date = timezone.now() - timedelta(days=1)
end_date = timezone.now() + timedelta(days=10)
@@ -103,9 +104,10 @@ def test_promotion_update_by_app(
update_products_discounted_prices_of_promotion_task_mock,
app_api_client,
permission_manage_discounts,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
promotion.start_date = timezone.now()
promotion.end_date = None
promotion.save(update_fields=["start_date", "end_date"])
@@ -160,9 +162,10 @@ def test_promotion_update_dates_dont_change(
update_products_discounted_prices_of_promotion_task_mock,
staff_api_client,
permission_group_manage_discounts,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
promotion.last_notification_scheduled_at = timezone.now() - timedelta(hours=1)
promotion.save(update_fields=["last_notification_scheduled_at"])
@@ -218,9 +221,10 @@ def test_promotion_update_by_customer(
promotion_ended_mock,
update_products_discounted_prices_of_promotion_task_mock,
api_client,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
start_date = timezone.now() + timedelta(days=1)
end_date = timezone.now() + timedelta(days=10)
@@ -248,7 +252,10 @@ def test_promotion_update_by_customer(
@freeze_time("2020-03-18 12:00:00")
def test_promotion_update_end_date_before_start_date(
- staff_api_client, permission_group_manage_discounts, description_json, promotion
+ staff_api_client,
+ permission_group_manage_discounts,
+ description_json,
+ catalogue_promotion,
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
@@ -257,7 +264,7 @@ def test_promotion_update_end_date_before_start_date(
new_promotion_name = "new test promotion"
variables = {
- "id": graphene.Node.to_global_id("Promotion", promotion.id),
+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id),
"input": {
"name": new_promotion_name,
"startDate": start_date.isoformat(),
@@ -336,7 +343,7 @@ def test_promotion_update_clears_old_sale_id(
def test_promotion_update_events(
- staff_api_client, permission_group_manage_discounts, promotion
+ staff_api_client, permission_group_manage_discounts, catalogue_promotion
):
# given
permission_group_manage_discounts.user_set.add(staff_api_client.user)
@@ -344,7 +351,7 @@ def test_promotion_update_events(
end_date = timezone.now() + timedelta(days=10)
variables = {
- "id": graphene.Node.to_global_id("Promotion", promotion.id),
+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.id),
"input": {
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
diff --git a/saleor/graphql/discount/tests/queries/test_promotion.py b/saleor/graphql/discount/tests/queries/test_promotion.py
index 5a91002cf7..d58c897b3f 100644
--- a/saleor/graphql/discount/tests/queries/test_promotion.py
+++ b/saleor/graphql/discount/tests/queries/test_promotion.py
@@ -29,6 +29,7 @@ QUERY_PROMOTION_BY_ID = """
rewardValueType
rewardValue
cataloguePredicate
+ rewardType
}
}
}
@@ -53,14 +54,16 @@ def _assert_promotion_data(promotion, content_data):
"rewardValueType": rule.reward_value_type.upper(),
"rewardValue": rule.reward_value,
"cataloguePredicate": rule.catalogue_predicate,
+ "rewardType": rule.reward_type,
}
assert rule_data in promotion_data["rules"]
def test_query_promotion_by_id_by_staff_user(
- promotion, staff_api_client, permission_group_manage_discounts
+ catalogue_promotion, staff_api_client, permission_group_manage_discounts
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
@@ -75,9 +78,10 @@ def test_query_promotion_by_id_by_staff_user(
def test_query_promotion_by_id_by_app(
- promotion, app_api_client, permission_manage_discounts
+ catalogue_promotion, app_api_client, permission_manage_discounts
):
# given
+ promotion = catalogue_promotion
app_api_client.app.permissions.add(permission_manage_discounts)
promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
variables = {"id": promotion_id}
@@ -90,8 +94,9 @@ def test_query_promotion_by_id_by_app(
_assert_promotion_data(promotion, content)
-def test_query_promotion_by_id_by_customer(promotion, api_client):
+def test_query_promotion_by_id_by_customer(catalogue_promotion, api_client):
# given
+ promotion = catalogue_promotion
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.id)}
# when
@@ -102,9 +107,10 @@ def test_query_promotion_by_id_by_customer(promotion, api_client):
def test_query_promotion_without_rules_by_id(
- promotion, staff_api_client, permission_group_manage_discounts
+ catalogue_promotion, staff_api_client, permission_group_manage_discounts
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
promotion.rules.all().delete()
@@ -119,7 +125,7 @@ def test_query_promotion_without_rules_by_id(
def test_query_promotion_with_complex_rule_2(
- promotion,
+ catalogue_promotion,
staff_api_client,
permission_group_manage_discounts,
product,
@@ -127,6 +133,7 @@ def test_query_promotion_with_complex_rule_2(
category,
):
# given
+ promotion = catalogue_promotion
permission_group_manage_discounts.user_set.add(staff_api_client.user)
promotion.rules.all().delete()
catalogue_predicate = {
@@ -160,7 +167,10 @@ def test_query_promotion_with_complex_rule_2(
def test_query_promotion_translation(
- staff_api_client, promotion, promotion_translation_fr, permission_manage_discounts
+ staff_api_client,
+ catalogue_promotion,
+ promotion_translation_fr,
+ permission_manage_discounts,
):
# given
query = """
@@ -177,7 +187,7 @@ def test_query_promotion_translation(
}
"""
- promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ promotion_id = graphene.Node.to_global_id("Promotion", catalogue_promotion.id)
# when
response = staff_api_client.post_graphql(
@@ -199,7 +209,7 @@ def test_query_promotion_translation(
def test_query_promotion_rule_translation(
staff_api_client,
- promotion,
+ catalogue_promotion,
promotion_rule_translation_fr,
permission_manage_discounts,
):
@@ -221,7 +231,7 @@ def test_query_promotion_rule_translation(
}
"""
- promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ promotion_id = graphene.Node.to_global_id("Promotion", catalogue_promotion.id)
# when
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/discount/tests/queries/test_promotions.py b/saleor/graphql/discount/tests/queries/test_promotions.py
index 702c972aa2..2404830704 100644
--- a/saleor/graphql/discount/tests/queries/test_promotions.py
+++ b/saleor/graphql/discount/tests/queries/test_promotions.py
@@ -109,7 +109,7 @@ QUERY_PROMOTIONS_PAGINATION = """
def test_query_promotions_pagination(
- promotion_list, promotion, staff_api_client, permission_manage_discounts
+ promotion_list, catalogue_promotion, staff_api_client, permission_manage_discounts
):
# given
end_cursor = None
diff --git a/saleor/graphql/discount/tests/queries/test_promotions_filtering.py b/saleor/graphql/discount/tests/queries/test_promotions_filtering.py
index 366939f84d..6647f8bc39 100644
--- a/saleor/graphql/discount/tests/queries/test_promotions_filtering.py
+++ b/saleor/graphql/discount/tests/queries/test_promotions_filtering.py
@@ -4,7 +4,9 @@ import graphene
import pytest
from django.utils import timezone
+from .....discount.models import Promotion
from ....tests.utils import get_graphql_content
+from ...enums import PromotionTypeEnum
QUERY_PROMOTIONS = """
query Promotions($where: PromotionWhereInput){
@@ -254,3 +256,74 @@ def test_query_promotions_filter_by_is_old_sale(
assert {promotion_list[index].name for index in indexes} == {
promotion["node"]["name"] for promotion in promotions
}
+
+
+ "filter_type",
+ [
+ PromotionTypeEnum.CATALOGUE,
+ PromotionTypeEnum.ORDER,
+ ],
+)
+def test_query_promotions_filter_type_eq(
+ filter_type, promotion_list, staff_api_client, permission_manage_discounts
+):
+ # given
+ promotion_with_order_type = promotion_list[:2]
+ Promotion.objects.filter(
+ id__in=[promotion.pk for promotion in promotion_with_order_type]
+ ).update(type=PromotionTypeEnum.ORDER.value)
+
+ input_type = filter_type.name
+ db_type = filter_type.value
+
+ variables = {"where": {"type": {"eq": input_type}}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PROMOTIONS, variables, permissions=(permission_manage_discounts,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ promotions = content["data"]["promotions"]["edges"]
+ db_promotions = Promotion.objects.filter(type=db_type)
+ assert len(promotions) == db_promotions.count()
+ names = {node["node"]["name"] for node in promotions}
+ assert names == {promotion.name for promotion in db_promotions}
+
+
+ "filter_type",
+ [
+ [PromotionTypeEnum.CATALOGUE],
+ [PromotionTypeEnum.ORDER],
+ [PromotionTypeEnum.ORDER, PromotionTypeEnum.CATALOGUE],
+ ],
+)
+def test_query_promotions_filter_type_one_of(
+ filter_type, promotion_list, staff_api_client, permission_manage_discounts
+):
+ # given
+ promotion_with_order_type = promotion_list[:2]
+ Promotion.objects.filter(
+ id__in=[promotion.pk for promotion in promotion_with_order_type]
+ ).update(type=PromotionTypeEnum.ORDER.value)
+
+ input_type = [promotion_type.name for promotion_type in filter_type]
+ db_type = [promotion_type.value for promotion_type in filter_type]
+
+ variables = {"where": {"type": {"oneOf": input_type}}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PROMOTIONS, variables, permissions=(permission_manage_discounts,)
+ )
+
+ # then
+ content = get_graphql_content(response)
+ promotions = content["data"]["promotions"]["edges"]
+ db_promotions = Promotion.objects.filter(type__in=db_type)
+ assert len(promotions) == db_promotions.count()
+ names = {node["node"]["name"] for node in promotions}
+ assert names == {promotion.name for promotion in db_promotions}
diff --git a/saleor/graphql/discount/tests/queries/test_promotions_sorting.py b/saleor/graphql/discount/tests/queries/test_promotions_sorting.py
index 91087f307c..ab3dfab8dc 100644
--- a/saleor/graphql/discount/tests/queries/test_promotions_sorting.py
+++ b/saleor/graphql/discount/tests/queries/test_promotions_sorting.py
@@ -28,11 +28,12 @@ QUERY_PROMOTIONS = """
def test_sorting_promotions_by_name(
direction,
staff_api_client,
- promotion,
+ catalogue_promotion,
promotion_list,
permission_manage_discounts,
):
# given
+ promotion = catalogue_promotion
promotion_list.insert(0, promotion)
variables = {
"sortBy": {
@@ -61,11 +62,12 @@ def test_sorting_promotions_by_name(
def test_sorting_promotions_by_end_date(
direction,
staff_api_client,
- promotion,
+ catalogue_promotion,
promotion_list,
permission_manage_discounts,
):
# given
+ promotion = catalogue_promotion
promotion_list.insert(2, promotion)
variables = {
"sortBy": {
@@ -94,11 +96,12 @@ def test_sorting_promotions_by_end_date(
def test_sorting_promotions_by_start_date(
direction,
staff_api_client,
- promotion,
+ catalogue_promotion,
promotion_list,
permission_manage_discounts,
):
# given
+ promotion = catalogue_promotion
promotion.start_date = timezone.now() + timedelta(days=3)
promotion.save(update_fields=["start_date"])
promotion_list.insert(1, promotion)
diff --git a/saleor/graphql/discount/tests/test_utils.py b/saleor/graphql/discount/tests/test_utils.py
index b1a5a5b3df..851aeef70d 100644
--- a/saleor/graphql/discount/tests/test_utils.py
+++ b/saleor/graphql/discount/tests/test_utils.py
@@ -5,13 +5,16 @@ import graphene
from ....discount import RewardValueType
from ....discount.models import Promotion, PromotionRule
from ..utils import (
+ _predicate_to_snake_case,
convert_migrated_sale_predicate_to_catalogue_info,
- get_variants_for_predicate,
+ get_variants_for_catalogue_predicate,
get_variants_for_promotion,
)
-def test_get_variants_for_predicate_with_or(product_with_two_variants, variant):
+def test_get_variants_for_catalogue_predicate_with_or(
+ product_with_two_variants, variant
+):
# given
catalogue_predicate = {
"OR": [
@@ -33,7 +36,7 @@ def test_get_variants_for_predicate_with_or(product_with_two_variants, variant):
}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert variant in variants
@@ -41,7 +44,7 @@ def test_get_variants_for_predicate_with_or(product_with_two_variants, variant):
assert variant in variants
-def test_get_variants_for_predicate_with_and(collection, product_list):
+def test_get_variants_for_catalogue_predicate_with_and(collection, product_list):
# given
product_in_collection = product_list[1]
collection.products.add(product_in_collection)
@@ -64,7 +67,7 @@ def test_get_variants_for_predicate_with_and(collection, product_list):
}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == product_in_collection.variants.count()
@@ -81,7 +84,7 @@ def test_get_variants_for_product_predicate(product_with_two_variants, variant):
}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == product_with_two_variants.variants.count()
@@ -102,7 +105,7 @@ def test_get_variants_for_variant_predicate(product_with_two_variants, variant):
}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == product_with_two_variants.variants.count()
@@ -125,7 +128,7 @@ def test_get_variants_for_category_predicate(
product.save(update_fields=["category"])
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == product.variants.count()
@@ -147,7 +150,7 @@ def test_get_variants_for_collection_predicate(
collection.products.add(product)
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == product.variants.count()
@@ -174,7 +177,7 @@ def test_get_variants_for_variant_and_empty_list_of_other_predicates(
}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == 0
@@ -207,14 +210,14 @@ def test_get_variants_for_variant_or_operator_and_empty_list_of_other_predicates
}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == product_with_two_variants.variants.count()
assert variant not in variants
-def test_get_variants_for_predicate_with_nested_conditions(
+def test_get_variants_for_catalogue_predicate_with_nested_conditions(
product_list, collection, variant
):
# given
@@ -250,7 +253,7 @@ def test_get_variants_for_predicate_with_nested_conditions(
}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == product_in_collection.variants.count() + 1
@@ -266,7 +269,7 @@ def test_get_variants_for_variant_predicate_empty_predicate_data(
catalogue_predicate = {}
# when
- variants = get_variants_for_predicate(catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(catalogue_predicate)
# then
assert len(variants) == 0
@@ -342,3 +345,80 @@ def test_convert_migrated_sale_predicate_to_catalogue_info(
# then
assert catalogue_info == expected_result
+
+
+def test_predicate_to_snake_case():
+ order_predicate = {
+ "AND": [
+ {
+ "discountedObjectPredicate": {
+ "OR": [
+ {
+ "discountedObjectPredicate": {
+ "userPredicate": {"isStaff": True}
+ }
+ },
+ {
+ "discountedObjectPredicate": {
+ "subtotalPrice": {"range": {"gte": 100}}
+ }
+ },
+ ]
+ }
+ },
+ {
+ "discountedLineObjectPredicate": {
+ "OR": [
+ {
+ "discountedLineObjectPredicate": {
+ "quantityAvailable": {"range": {"gte": 3}}
+ }
+ },
+ {"discountedLineObjectPredicate": {"name": {"eq": "Shirt"}}},
+ {
+ "discountedLineObjectPredicate": {
+ "mainTitle": {"oneOf": [1, "ABC", "Yo"]}
+ }
+ },
+ ]
+ }
+ },
+ ]
+ }
+ assert _predicate_to_snake_case(order_predicate) == {
+ "AND": [
+ {
+ "discounted_object_predicate": {
+ "OR": [
+ {
+ "discounted_object_predicate": {
+ "user_predicate": {"is_staff": True}
+ }
+ },
+ {
+ "discounted_object_predicate": {
+ "subtotal_price": {"range": {"gte": 100}}
+ }
+ },
+ ]
+ }
+ },
+ {
+ "discounted_line_object_predicate": {
+ "OR": [
+ {
+ "discounted_line_object_predicate": {
+ "quantity_available": {"range": {"gte": 3}}
+ }
+ },
+ {"discounted_line_object_predicate": {"name": {"eq": "Shirt"}}},
+ {
+ "discounted_line_object_predicate": {
+ "main_title": {"oneOf": [1, "ABC", "Yo"]}
+ }
+ },
+ ]
+ }
+ },
+ ]
+ }
diff --git a/saleor/graphql/discount/tests/test_validators.py b/saleor/graphql/discount/tests/test_validators.py
index c177f5ce1f..6e47c3b60e 100644
--- a/saleor/graphql/discount/tests/test_validators.py
+++ b/saleor/graphql/discount/tests/test_validators.py
@@ -1,9 +1,19 @@
+from collections import defaultdict
+
import graphene
import pytest
from django.core.exceptions import ValidationError
-from ....discount.error_codes import PromotionCreateErrorCode
-from ..mutations.promotion.validators import clean_predicate
+from ....discount import PromotionType, RewardType, RewardValueType
+from ..enums import PromotionCreateErrorCode
+from ..mutations.promotion.validators import (
+ _clean_catalogue_predicate,
+ _clean_order_predicate,
+ _clean_predicates,
+ _clean_reward,
+ _clean_reward_value,
+ clean_predicate,
+)
def test_clean_predicate(variant, product):
@@ -53,3 +63,526 @@ def test_clean_predicate_invalid_predicate(predicate):
# then
assert validation_error.value.code == PromotionCreateErrorCode.INVALID.value
+
+
+def test_clean_predicates_invalid_order_predicate(product):
+ # given
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ catalogue_predicate = {
+ "product_predicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_predicates(
+ catalogue_predicate,
+ order_predicate,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ PromotionType.CATALOGUE,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["order_predicate"]) == 1
+ assert errors["order_predicate"][0].code == PromotionCreateErrorCode.INVALID.value
+
+
+def test_clean_predicates_invalid_catalogue_predicate(product):
+ # given
+ checkout_and_order_predicate = {
+ "discounted_object_predicate": {"subtotal_price": {"range": {"gte": 100}}}
+ }
+ catalogue_predicate = {
+ "product_predicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_predicates(
+ catalogue_predicate,
+ checkout_and_order_predicate,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ PromotionType.ORDER,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["catalogue_predicate"]) == 1
+ assert (
+ errors["catalogue_predicate"][0].code == PromotionCreateErrorCode.INVALID.value
+ )
+
+
+def test_clean_predicates_missing_catalogue_predicate(product):
+ # given
+ errors = defaultdict(list)
+
+ # when
+ _clean_predicates(
+ None,
+ None,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ PromotionType.CATALOGUE,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["catalogue_predicate"]) == 1
+ assert (
+ errors["catalogue_predicate"][0].code == PromotionCreateErrorCode.REQUIRED.value
+ )
+
+
+def test_clean_predicates_missing_order_predicate(product):
+ # given
+ errors = defaultdict(list)
+
+ # when
+ _clean_predicates(
+ None,
+ None,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ PromotionType.ORDER,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["order_predicate"]) == 1
+ assert errors["order_predicate"][0].code == PromotionCreateErrorCode.REQUIRED.value
+
+
+def test_clean_predicates_mixed_promotion_predicates_invalid_catalogue_predicate(
+ product,
+):
+ # given
+ catalogue_predicate = {
+ "product_predicate": {
+ "ids": [graphene.Node.to_global_id("Product", product.id)]
+ }
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_predicates(
+ catalogue_predicate,
+ {},
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ PromotionType.ORDER,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["catalogue_predicate"]) == 1
+ assert (
+ errors["catalogue_predicate"][0].code == PromotionCreateErrorCode.INVALID.value
+ )
+
+
+def test_clean_predicates_mixed_promotion_predicates_invalid_order(
+ product,
+):
+ # given
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_predicates(
+ {},
+ order_predicate,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ PromotionType.CATALOGUE,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["order_predicate"]) == 1
+ assert errors["order_predicate"][0].code == PromotionCreateErrorCode.INVALID.value
+
+
+def test_clean_catalogue_predicate_reward_type_provided():
+ # given
+ catalogue_predicate = {
+ "productPredicate": {"ids": ["ABC"]},
+ "categoryPredicate": {"ids": ["ABC"]},
+ }
+ cleaned_input = {
+ "catalogue_predicate": catalogue_predicate,
+ "reward_type": RewardType.SUBTOTAL_DISCOUNT,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_catalogue_predicate(
+ cleaned_input,
+ catalogue_predicate,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["reward_type"]) == 1
+ assert errors["reward_type"][0].code == PromotionCreateErrorCode.INVALID.value
+
+
+def test_clean_order_predicate_missing_reward_type():
+ # given
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "order_predicate": order_predicate,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_order_predicate(
+ cleaned_input,
+ order_predicate,
+ {},
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["reward_type"]) == 1
+ assert errors["reward_type"][0].code == PromotionCreateErrorCode.REQUIRED.value
+
+
+def test_clean_order_predicate_reward_type_in_instance(
+ order_promotion_with_rule,
+):
+ # given
+ rule = order_promotion_with_rule.rules.first()
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "order_predicate": order_predicate,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_order_predicate(
+ cleaned_input,
+ order_predicate,
+ {},
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ rule,
+ )
+
+ # then
+ assert not errors
+
+
+def test_clean_order_predicate_price_based_predicate_mixed_currencies():
+ # given
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "order_predicate": order_predicate,
+ "reward_type": RewardType.SUBTOTAL_DISCOUNT,
+ }
+ currencies = {"USD", "PLN"}
+ errors = defaultdict(list)
+
+ # when
+ _clean_order_predicate(
+ cleaned_input,
+ order_predicate,
+ currencies,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["channels"]) == 1
+ assert (
+ errors["channels"][0].code
+ == PromotionCreateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.value
+ )
+
+
+def test_clean_order_mixed_currencies_instance_given_invalid_predicate(
+ order_promotion_with_rule,
+):
+ # given
+ rule = order_promotion_with_rule.rules.first()
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "order_predicate": order_predicate,
+ }
+ currencies = {"USD", "PLN"}
+ errors = defaultdict(list)
+
+ # when
+ _clean_order_predicate(
+ cleaned_input,
+ order_predicate,
+ currencies,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ rule,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["order_predicate"]) == 1
+ assert (
+ errors["order_predicate"][0].code
+ == PromotionCreateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.value
+ )
+
+
+def test_clean_order_mixed_currencies_instance_given_invalid_channels(
+ order_promotion_with_rule,
+):
+ # given
+ rule = order_promotion_with_rule.rules.first()
+ order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "add_channels": ["AB", "CD"],
+ }
+ currencies = {"USD", "PLN"}
+ errors = defaultdict(list)
+
+ # when
+ _clean_order_predicate(
+ cleaned_input,
+ order_predicate,
+ currencies,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ rule,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["add_channels"]) == 1
+ assert (
+ errors["add_channels"][0].code
+ == PromotionCreateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.value
+ )
+
+
+def test_clean_reward_lack_of_reward_value_type():
+ # given
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "order_predicate": order_predicate,
+ "reward_value": 10,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_reward(
+ cleaned_input,
+ {},
+ order_predicate,
+ {},
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["reward_value_type"]) == 1
+ assert (
+ errors["reward_value_type"][0].code == PromotionCreateErrorCode.REQUIRED.value
+ )
+
+
+def test_clean_reward_no_reward_value():
+ # given
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "order_predicate": order_predicate,
+ "reward_value_type": RewardValueType.FIXED,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_reward(
+ cleaned_input,
+ {},
+ order_predicate,
+ {},
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["reward_value"]) == 1
+ assert errors["reward_value"][0].code == PromotionCreateErrorCode.REQUIRED.value
+
+
+def test_clean_reward_lack_of_reward_value_and_reward_value_type():
+ # given
+ order_predicate = {
+ "discounted_object_predicate": {"base_subtotal_price": {"range": {"gte": 100}}}
+ }
+ cleaned_input = {
+ "order_predicate": order_predicate,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_reward(
+ cleaned_input,
+ {},
+ order_predicate,
+ {},
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 2
+ assert len(errors["reward_value_type"]) == 1
+ assert (
+ errors["reward_value_type"][0].code == PromotionCreateErrorCode.REQUIRED.value
+ )
+ assert len(errors["reward_value"]) == 1
+ assert errors["reward_value"][0].code == PromotionCreateErrorCode.REQUIRED.value
+
+
+def test_clean_reward_value_missing_channels():
+ # given
+ reward_type = RewardType.SUBTOTAL_DISCOUNT
+ reward_value = 10
+ reward_value_type = RewardValueType.FIXED
+ channel_currencies = {}
+ cleaned_input = {
+ "reward_value": reward_value,
+ "reward_type": reward_type,
+ "reward_value_type": reward_value_type,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_reward_value(
+ cleaned_input,
+ reward_value,
+ reward_value_type,
+ channel_currencies,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["channels"]) == 1
+ assert errors["channels"][0].code == PromotionCreateErrorCode.MISSING_CHANNELS.value
+
+
+def test_clean_reward_value_multiple_currencies():
+ # given
+ reward_type = RewardType.SUBTOTAL_DISCOUNT
+ reward_value = 10
+ reward_value_type = RewardValueType.FIXED
+ channel_currencies = {"USD", "PLN"}
+ cleaned_input = {
+ "reward_value": reward_value,
+ "reward_type": reward_type,
+ "reward_value_type": reward_value_type,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_reward_value(
+ cleaned_input,
+ reward_value,
+ reward_value_type,
+ channel_currencies,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert len(errors) == 1
+ assert len(errors["reward_value_type"]) == 1
+ assert (
+ errors["reward_value_type"][0].code
+ == PromotionCreateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.value
+ )
+
+
+def test_clean_reward_value_multiple_currencies_error_not_raised_for_percentage_disc():
+ # given
+ reward_type = RewardType.SUBTOTAL_DISCOUNT
+ reward_value = 10
+ reward_value_type = RewardValueType.PERCENTAGE
+ channel_currencies = {"USD", "PLN"}
+ cleaned_input = {
+ "reward_value": reward_value,
+ "reward_type": reward_type,
+ "reward_value_type": reward_value_type,
+ }
+ errors = defaultdict(list)
+
+ # when
+ _clean_reward_value(
+ cleaned_input,
+ reward_value,
+ reward_value_type,
+ channel_currencies,
+ errors,
+ PromotionCreateErrorCode,
+ None,
+ None,
+ )
+
+ # then
+ assert not errors
diff --git a/saleor/graphql/discount/types/promotions.py b/saleor/graphql/discount/types/promotions.py
index 52b539ac09..5a8187d64a 100644
--- a/saleor/graphql/discount/types/promotions.py
+++ b/saleor/graphql/discount/types/promotions.py
@@ -6,7 +6,7 @@ from ....permission.auth_filters import AuthorizationFilters
from ...channel.types import Channel
from ...core import ResolveInfo
from ...core.connection import CountableConnection
-from ...core.descriptions import ADDED_IN_317, PREVIEW_FEATURE
+from ...core.descriptions import ADDED_IN_317, ADDED_IN_319, PREVIEW_FEATURE
from ...core.doc_category import DOC_CATEGORY_DISCOUNTS
from ...core.fields import PermissionsField
from ...core.scalars import JSON, PositiveDecimal
@@ -20,13 +20,19 @@ from ..dataloaders import (
PromotionEventsByPromotionIdLoader,
PromotionRulesByPromotionIdLoader,
)
-from ..enums import RewardValueTypeEnum
+from ..enums import PromotionTypeEnum, RewardTypeEnum, RewardValueTypeEnum
from .promotion_events import PromotionEvent
class Promotion(ModelObjectType[models.Promotion]):
id = graphene.GlobalID(required=True)
name = graphene.String(required=True, description="Name of the promotion.")
+ type = PromotionTypeEnum(
+ description=(
+ "The type of the promotion. Implicate if the discount is applied on "
+ "catalogue or order level." + ADDED_IN_319 + PREVIEW_FEATURE
+ )
+ )
description = JSON(description="Description of the promotion.")
start_date = graphene.DateTime(
required=True, description="Start date of the promotion."
@@ -82,19 +88,38 @@ class PromotionRule(ModelObjectType[models.PromotionRule]):
AuthorizationFilters.AUTHENTICATED_STAFF_USER,
],
)
+ reward_value = PositiveDecimal(
+ description=(
+ "The reward value of the promotion rule. Defines the discount value "
+ "applied when the rule conditions are met." + ADDED_IN_319 + PREVIEW_FEATURE
+ )
+ )
reward_value_type = RewardValueTypeEnum(
description="The type of reward value of the promotion rule."
)
+ predicate_type = PromotionTypeEnum(
+ description=(
+ "The type of the predicate that must be met to apply the reward."
+ + ADDED_IN_319
+ + PREVIEW_FEATURE
+ )
+ )
catalogue_predicate = JSON(
description=(
"The catalogue predicate that must be met to apply the rule reward."
),
)
- reward_value = PositiveDecimal(
+ order_predicate = JSON(
description=(
- "The reward value of the promotion rule. Defines the discount value "
- "applied when the rule conditions are met."
- )
+ "The checkout/order predicate that must be met to apply the rule reward."
+ + ADDED_IN_319
+ + PREVIEW_FEATURE
+ ),
+ )
+ reward_type = RewardTypeEnum(
+ description="The reward type of the promotion rule."
+ + ADDED_IN_319
+ + PREVIEW_FEATURE
)
translation = TranslationField(PromotionRuleTranslation, type_name="promotion rule")
@@ -111,6 +136,17 @@ class PromotionRule(ModelObjectType[models.PromotionRule]):
def resolve_promotion(root: models.PromotionRule, info: ResolveInfo):
return PromotionByIdLoader(info.context).load(root.promotion_id)
+ @staticmethod
+ def resolve_predicate_type(root: models.PromotionRule, info: ResolveInfo):
+ def with_promotion(promotion):
+ return promotion.type
+
+ return (
+ PromotionByIdLoader(info.context)
+ .load(root.promotion_id)
+ .then(with_promotion)
+ )
+
@staticmethod
def resolve_channels(root: models.PromotionRule, info: ResolveInfo):
return ChannelsByPromotionRuleIdLoader(info.context).load(root.id)
diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.py
index 3efd22cf17..458a7c1dba 100644
--- a/saleor/graphql/discount/utils.py
+++ b/saleor/graphql/discount/utils.py
@@ -1,12 +1,13 @@
from collections import defaultdict
from copy import deepcopy
from enum import Enum
-from typing import Optional, Union, cast
+from typing import Any, Optional, Union, cast
import graphene
from django.db.models import Exists, OuterRef, QuerySet
-from graphene.utils.str_converters import to_camel_case
+from graphene.utils.str_converters import to_snake_case
+from ...checkout.models import Checkout
from ...discount.models import Promotion, PromotionRule
from ...discount.utils import update_rule_variant_relation
from ...product.managers import ProductsQueryset, ProductVariantQueryset
@@ -17,6 +18,7 @@ from ...product.models import (
Product,
ProductVariant,
)
+from ..checkout.filters import CheckoutDiscountedObjectWhere
from ..core.connection import where_filter_qs
from ..product.filters import (
CategoryWhere,
@@ -28,27 +30,17 @@ from ..product.filters import (
PREDICATE_OPERATOR_DATA_T = list[dict[str, Union[list, dict, str, bool]]]
+class PredicateObjectType(Enum):
+ CATALOGUE = "catalogue"
+ CHECKOUT = "checkout"
+ ORDER = "order"
+
+
class Operators(Enum):
AND = "and"
OR = "or"
-# TODO: move to validators in promotion dir
-def clean_predicate(predicate: Union[dict[str, Union[dict, list]], list]):
- """Convert camel cases keys into snake case."""
- if isinstance(predicate, list):
- return [
- clean_predicate(item) if isinstance(item, (dict, list)) else item
- for item in predicate
- ]
- return {
- to_camel_case(key): clean_predicate(value)
- if isinstance(value, (dict, list))
- else value
- for key, value in predicate.items()
- }
-
-
def get_products_for_promotion(
promotion: Promotion, *, update_rule_variants=False
) -> ProductsQueryset:
@@ -63,7 +55,7 @@ def get_products_for_rule(
rule: PromotionRule, *, update_rule_variants=False
) -> ProductsQueryset:
"""Get products that are included in the rule based on catalogue predicate."""
- variants = get_variants_for_predicate(deepcopy(rule.catalogue_predicate))
+ variants = get_variants_for_catalogue_predicate(deepcopy(rule.catalogue_predicate))
if update_rule_variants:
rule.variants.set(variants)
return Product.objects.filter(Exists(variants.filter(product_id=OuterRef("id"))))
@@ -78,7 +70,7 @@ def get_variants_for_promotion(
PromotionRuleVariant = PromotionRule.variants.through
rules = promotion.rules.all()
for rule in rules:
- variants = get_variants_for_predicate(rule.catalogue_predicate)
+ variants = get_variants_for_catalogue_predicate(rule.catalogue_predicate)
queryset |= variants
if update_rule_variants:
promotion_rule_variants.extend(
@@ -96,10 +88,14 @@ def get_variants_for_promotion(
def _handle_product_predicate(
- predicate_data: dict[str, Union[dict, list]],
+ predicate_data: dict[str, Union[dict, list]], variant_qs: QuerySet[ProductVariant]
) -> ProductVariantQueryset:
product_qs = where_filter_qs(
- Product.objects.all(), {}, ProductWhere, predicate_data, None
+ Product.objects.filter(Exists(variant_qs.filter(product_id=OuterRef("id")))),
+ {},
+ ProductWhere,
+ predicate_data,
+ None,
)
return ProductVariant.objects.filter(
Exists(product_qs.filter(id=OuterRef("product_id")))
@@ -107,35 +103,50 @@ def _handle_product_predicate(
def _handle_variant_predicate(
- predicate_data: dict[str, Union[dict, list]],
+ predicate_data: dict[str, Union[dict, list]], variant_qs: QuerySet[ProductVariant]
) -> ProductVariantQueryset:
return where_filter_qs(
- ProductVariant.objects.all(), {}, ProductVariantWhere, predicate_data, None
+ ProductVariant.objects.filter(id__in=variant_qs.values("id")),
+ {},
+ ProductVariantWhere,
+ predicate_data,
+ None,
)
def _handle_collection_predicate(
- predicate_data: dict[str, Union[dict, list]],
+ predicate_data: dict[str, Union[dict, list]], variant_qs: QuerySet[ProductVariant]
) -> ProductVariantQueryset:
+ collection_products = CollectionProduct.objects.filter(
+ product_id__in=variant_qs.values("product_id")
+ )
collection_qs = where_filter_qs(
- Collection.objects.all(), {}, CollectionWhere, predicate_data, None
+ Collection.objects.filter(
+ Exists(collection_products.filter(collection_id=OuterRef("id")))
+ ),
+ {},
+ CollectionWhere,
+ predicate_data,
+ None,
)
collection_products = CollectionProduct.objects.filter(
Exists(collection_qs.filter(id=OuterRef("collection_id")))
)
- products = Product.objects.filter(
- Exists(collection_products.filter(product_id=OuterRef("id")))
- )
return ProductVariant.objects.filter(
- Exists(products.filter(id=OuterRef("product_id")))
+ Exists(collection_products.filter(product_id=OuterRef("product_id")))
)
def _handle_category_predicate(
- predicate_data: dict[str, Union[dict, list]],
+ predicate_data: dict[str, Union[dict, list]], variant_qs
) -> ProductVariantQueryset:
+ products = Product.objects.filter(id__in=variant_qs.values("product_id"))
category_qs = where_filter_qs(
- Category.objects.all(), {}, CategoryWhere, predicate_data, None
+ Category.objects.filter(Exists(products.filter(category_id=OuterRef("id")))),
+ {},
+ CategoryWhere,
+ predicate_data,
+ None,
)
products = Product.objects.filter(
Exists(category_qs.filter(id=OuterRef("category_id")))
@@ -153,73 +164,184 @@ PREDICATE_TO_HANDLE_METHOD = {
}
-def get_variants_for_predicate(
- predicate: dict, queryset: Optional[ProductVariantQueryset] = None
-) -> ProductVariantQueryset:
- """Get variants that met the predicate conditions."""
+def get_variants_for_catalogue_predicate(
+ predicate, queryset: Optional[ProductVariantQueryset] = None
+):
if not predicate:
return ProductVariant.objects.none()
-
if queryset is None:
queryset = ProductVariant.objects.all()
+ return filter_qs_by_predicate(predicate, queryset, PredicateObjectType.CATALOGUE)
+
+
+def filter_qs_by_predicate(
+ predicate: dict,
+ base_qs: QuerySet,
+ predicate_type: PredicateObjectType,
+ currency: Optional[str] = None,
+ *,
+ result_qs: Optional[QuerySet] = None,
+) -> QuerySet:
+ """Filter QuerySet by predicate conditions.
+
+ Args:
+ predicate: dict with conditions
+ result_qs: QuerySet that contains results of previous conditions
+ base_qs: QuerySet that contains all objects that can be filtered
+ predicate_type: type of predicate (catalogue or order)
+ currency: currency used for filtering by order predicates
+ with price conditions
+ """
+ if not predicate:
+ return base_qs.model.objects.none()
+
+ if result_qs is None:
+ result_qs = base_qs
+
+ result_qs = cast(QuerySet, result_qs)
+
and_data: Optional[list[dict]] = predicate.pop("AND", None)
or_data: Optional[list[dict]] = predicate.pop("OR", None)
if and_data:
- queryset = _handle_and_data(queryset, and_data)
-
+ result_qs = _handle_and_data(
+ result_qs, base_qs, and_data, predicate_type, currency
+ )
if or_data:
- queryset = _handle_or_data(queryset, or_data)
-
+ result_qs = _handle_or_data(
+ result_qs, base_qs, or_data, predicate_type, currency
+ )
if predicate:
- queryset = _handle_catalogue_predicate(queryset, predicate, Operators.AND)
+ result_qs = _handle_predicate(
+ result_qs, base_qs, predicate, Operators.AND, predicate_type, currency
+ )
- return queryset
+ return result_qs
def _handle_and_data(
- queryset: ProductVariantQueryset, data: PREDICATE_OPERATOR_DATA_T
-) -> ProductVariantQueryset:
+ result_qs: QuerySet,
+ base_qs: QuerySet,
+ data: PREDICATE_OPERATOR_DATA_T,
+ predicate_type: PredicateObjectType,
+ currency: Optional[str] = None,
+) -> QuerySet:
for predicate_data in data:
if contains_filter_operator(predicate_data):
- queryset &= get_variants_for_predicate(predicate_data, queryset)
+ result_qs &= filter_qs_by_predicate(
+ predicate_data, base_qs, predicate_type, currency, result_qs=result_qs
+ )
else:
- queryset = _handle_catalogue_predicate(
- queryset, predicate_data, Operators.AND
+ result_qs = _handle_predicate(
+ result_qs,
+ base_qs,
+ predicate_data,
+ Operators.AND,
+ predicate_type,
+ currency,
)
- return queryset
+ return result_qs
def _handle_or_data(
- queryset: ProductVariantQueryset, data: PREDICATE_OPERATOR_DATA_T
-) -> ProductVariantQueryset:
- qs = queryset.model.objects.none()
+ result_qs: QuerySet,
+ base_qs: QuerySet,
+ data: PREDICATE_OPERATOR_DATA_T,
+ predicate_type: PredicateObjectType,
+ currency: Optional[str] = None,
+) -> QuerySet:
+ qs = result_qs.model.objects.none()
for predicate_data in data:
if contains_filter_operator(predicate_data):
- qs |= get_variants_for_predicate(predicate_data, queryset)
+ qs |= filter_qs_by_predicate(
+ predicate_data, base_qs, predicate_type, currency, result_qs=result_qs
+ )
else:
- qs = _handle_catalogue_predicate(qs, predicate_data, Operators.OR)
- queryset &= qs
- return queryset
+ qs = _handle_predicate(
+ qs, base_qs, predicate_data, Operators.OR, predicate_type, currency
+ )
+ result_qs &= qs
+ return result_qs
def contains_filter_operator(input: dict[str, Union[dict, str, list, bool]]) -> bool:
return any([operator in input for operator in ["AND", "OR", "NOT"]])
+def _handle_predicate(
+ result_qs: QuerySet,
+ base_qs: QuerySet,
+ predicate_data: dict[str, Union[dict, str, list, bool]],
+ operator: Operators,
+ predicate_type: PredicateObjectType,
+ currency: Optional[str] = None,
+):
+ if predicate_type == PredicateObjectType.CATALOGUE:
+ return _handle_catalogue_predicate(result_qs, base_qs, predicate_data, operator)
+ elif predicate_type == PredicateObjectType.CHECKOUT:
+ return _handle_checkout_predicate(
+ result_qs, base_qs, predicate_data, operator, currency
+ )
+
+
def _handle_catalogue_predicate(
- queryset: ProductVariantQueryset,
+ result_qs: QuerySet,
+ base_qs: QuerySet,
predicate_data: dict[str, Union[dict, str, list, bool]],
operator,
-) -> ProductVariantQueryset:
+) -> QuerySet[ProductVariant]:
for field, handle_method in PREDICATE_TO_HANDLE_METHOD.items():
if field_data := predicate_data.get(field):
field_data = cast(dict[str, Union[dict, list]], field_data)
if operator == Operators.AND:
- queryset &= handle_method(field_data)
+ result_qs &= handle_method(field_data, base_qs)
else:
- queryset |= handle_method(field_data)
- return queryset
+ result_qs |= handle_method(field_data, base_qs)
+ return result_qs
+
+
+def _handle_checkout_predicate(
+ result_qs: QuerySet,
+ base_qs: QuerySet,
+ predicate_data: dict[str, Union[dict, str, list, bool]],
+ operator,
+ currency: Optional[str] = None,
+):
+ predicate_data = _predicate_to_snake_case(predicate_data)
+ if predicate := predicate_data.get("discounted_object_predicate"):
+ if currency:
+ predicate["currency"] = currency
+
+ checkouts = where_filter_qs(
+ Checkout.objects.filter(pk__in=base_qs.values("pk")),
+ {},
+ CheckoutDiscountedObjectWhere,
+ predicate,
+ None,
+ )
+ if operator == Operators.AND:
+ result_qs &= checkouts
+ else:
+ result_qs |= checkouts
+ return result_qs
+
+
+def _predicate_to_snake_case(obj: Any) -> Any:
+ if isinstance(obj, dict):
+ data = {}
+ for key, value in obj.items():
+ if key in ["AND", "OR"]:
+ data[key] = _predicate_to_snake_case(value)
+ elif key in ["eq", "oneOf"]:
+ data[key] = value
+ else:
+ data[_predicate_to_snake_case(key)] = _predicate_to_snake_case(value)
+ return data
+ if isinstance(obj, list):
+ return [_predicate_to_snake_case(item) for item in obj]
+ if isinstance(obj, str):
+ return to_snake_case(obj)
+ return obj
def convert_migrated_sale_predicate_to_model_ids(
diff --git a/saleor/graphql/meta/tests/mutations/test_discount.py b/saleor/graphql/meta/tests/mutations/test_discount.py
index 68056b281c..bd022d0b67 100644
--- a/saleor/graphql/meta/tests/mutations/test_discount.py
+++ b/saleor/graphql/meta/tests/mutations/test_discount.py
@@ -153,10 +153,10 @@ def test_add_private_metadata_for_voucher(
def test_add_public_metadata_for_promotion(
- staff_api_client, permission_manage_discounts, promotion
+ staff_api_client, permission_manage_discounts, catalogue_promotion
):
# given
- promotion_id = graphene.Node.to_global_id("Promotion", promotion.pk)
+ promotion_id = graphene.Node.to_global_id("Promotion", catalogue_promotion.pk)
# when
response = execute_update_public_metadata_for_item(
@@ -165,14 +165,15 @@ def test_add_public_metadata_for_promotion(
# then
assert item_contains_proper_public_metadata(
- response["data"]["updateMetadata"]["item"], promotion, promotion_id
+ response["data"]["updateMetadata"]["item"], catalogue_promotion, promotion_id
)
def test_delete_public_metadata_for_promotion(
- staff_api_client, permission_manage_discounts, promotion
+ staff_api_client, permission_manage_discounts, catalogue_promotion
):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
promotion.save(update_fields=["metadata"])
promotion_id = graphene.Node.to_global_id("Promotion", promotion.pk)
@@ -189,9 +190,10 @@ def test_delete_public_metadata_for_promotion(
def test_add_private_metadata_for_promotion(
- staff_api_client, permission_manage_discounts, promotion
+ staff_api_client, permission_manage_discounts, catalogue_promotion
):
# given
+ promotion = catalogue_promotion
promotion_id = graphene.Node.to_global_id("Promotion", promotion.pk)
# when
@@ -206,9 +208,10 @@ def test_add_private_metadata_for_promotion(
def test_delete_private_metadata_for_promotion(
- staff_api_client, permission_manage_discounts, promotion
+ staff_api_client, permission_manage_discounts, catalogue_promotion
):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
promotion.save(update_fields=["private_metadata"])
promotion_id = graphene.Node.to_global_id("Promotion", promotion.pk)
diff --git a/saleor/graphql/meta/tests/queries/test_discount.py b/saleor/graphql/meta/tests/queries/test_discount.py
index 14fc43e486..6aaceaec10 100644
--- a/saleor/graphql/meta/tests/queries/test_discount.py
+++ b/saleor/graphql/meta/tests/queries/test_discount.py
@@ -379,8 +379,11 @@ QUERY_PROMOTION_PUBLIC_META = """
"""
-def test_query_public_meta_for_promotion_as_anonymous_user(api_client, promotion):
+def test_query_public_meta_for_promotion_as_anonymous_user(
+ api_client, catalogue_promotion
+):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
promotion.save(update_fields=["metadata"])
variables = {
@@ -394,8 +397,11 @@ def test_query_public_meta_for_promotion_as_anonymous_user(api_client, promotion
assert_no_permission(response)
-def test_query_public_meta_for_promotion_as_customer(user_api_client, promotion):
+def test_query_public_meta_for_promotion_as_customer(
+ user_api_client, catalogue_promotion
+):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
promotion.save(update_fields=["metadata"])
variables = {
@@ -410,9 +416,10 @@ def test_query_public_meta_for_promotion_as_customer(user_api_client, promotion)
def test_query_public_meta_for_promotion_as_staff(
- staff_api_client, promotion, permission_manage_discounts
+ staff_api_client, catalogue_promotion, permission_manage_discounts
):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
promotion.save(update_fields=["metadata"])
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.pk)}
@@ -433,9 +440,10 @@ def test_query_public_meta_for_promotion_as_staff(
def test_query_public_meta_for_promotion_as_app(
- app_api_client, promotion, permission_manage_discounts
+ app_api_client, catalogue_promotion, permission_manage_discounts
):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
promotion.save(update_fields=["metadata"])
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.pk)}
@@ -467,10 +475,12 @@ QUERY_PROMOTION_PRIVATE_META = """
"""
-def test_query_private_meta_for_promotion_as_anonymous_user(api_client, promotion):
+def test_query_private_meta_for_promotion_as_anonymous_user(
+ api_client, catalogue_promotion
+):
# given
variables = {
- "id": graphene.Node.to_global_id("Promotion", promotion.pk),
+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.pk),
}
# when
@@ -480,10 +490,12 @@ def test_query_private_meta_for_promotion_as_anonymous_user(api_client, promotio
assert_no_permission(response)
-def test_query_private_meta_for_promotion_as_customer(user_api_client, promotion):
+def test_query_private_meta_for_promotion_as_customer(
+ user_api_client, catalogue_promotion
+):
# given
variables = {
- "id": graphene.Node.to_global_id("Promotion", promotion.pk),
+ "id": graphene.Node.to_global_id("Promotion", catalogue_promotion.pk),
}
# when
@@ -494,9 +506,10 @@ def test_query_private_meta_for_promotion_as_customer(user_api_client, promotion
def test_query_private_meta_for_promotion_as_staff(
- staff_api_client, promotion, permission_manage_discounts
+ staff_api_client, catalogue_promotion, permission_manage_discounts
):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
promotion.save(update_fields=["private_metadata"])
variables = {"id": graphene.Node.to_global_id("Promotion", promotion.pk)}
@@ -517,9 +530,10 @@ def test_query_private_meta_for_promotion_as_staff(
def test_query_private_meta_for_promotion_as_app(
- app_api_client, promotion, permission_manage_discounts
+ app_api_client, catalogue_promotion, permission_manage_discounts
):
# given
+ promotion = catalogue_promotion
promotion.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
promotion.save(update_fields=["private_metadata"])
variables = {
diff --git a/saleor/graphql/order/tests/benchmark/test_order_lines_create.py b/saleor/graphql/order/tests/benchmark/test_order_lines_create.py
index e981ad627f..e6df46982c 100644
--- a/saleor/graphql/order/tests/benchmark/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/benchmark/test_order_lines_create.py
@@ -79,9 +79,10 @@ def test_order_lines_create_variants_on_promotion(
staff_api_client,
product_list,
count_queries,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
query = ORDER_LINES_CREATE_MUTATION
order = order_with_lines
order.status = OrderStatus.DRAFT
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 af64c2c52a..bb5d8d14d3 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -2296,12 +2296,12 @@ def test_draft_order_create_product_on_promotion(
customer_user,
shipping_method,
variant,
- promotion,
+ catalogue_promotion,
channel_USD,
graphql_address_data,
):
# given
- variant = variant
+ promotion = catalogue_promotion
query = DRAFT_ORDER_CREATE_MUTATION
permission_group_manage_orders.user_set.add(staff_api_client.user)
@@ -2422,12 +2422,12 @@ def test_draft_order_create_product_on_promotion_flat_taxes(
customer_user,
shipping_method,
variant,
- promotion,
+ catalogue_promotion,
channel_USD,
graphql_address_data,
):
# given
- variant = variant
+ promotion = catalogue_promotion
query = DRAFT_ORDER_CREATE_MUTATION
permission_group_manage_orders.user_set.add(staff_api_client.user)
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 6184c4fdbb..da5680b589 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -542,7 +542,7 @@ def test_order_lines_create_variant_on_promotion(
permission_group_manage_orders,
staff_api_client,
variant_with_many_stocks,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
promotion_translation_fr,
promotion_rule_translation_fr,
):
@@ -556,7 +556,7 @@ def test_order_lines_create_variant_on_promotion(
variant = variant_with_many_stocks
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -580,7 +580,7 @@ def test_order_lines_create_variant_on_promotion(
currency=order.channel.currency_code,
)
- promotion_translation_fr.promotion = promotion_without_rules
+ promotion_translation_fr.promotion = catalogue_promotion_without_rules
promotion_translation_fr.language_code = order.language_code
promotion_translation_fr.save(update_fields=["promotion", "language_code"])
@@ -622,12 +622,12 @@ def test_order_lines_create_variant_on_promotion(
== variant_channel_listing.price_amount - reward_value
)
assert line_data["saleId"] == graphene.Node.to_global_id(
- "Promotion", promotion_without_rules.id
+ "Promotion", catalogue_promotion_without_rules.id
)
line = order.lines.get(product_sku=variant.sku)
assert line.sale_id == graphene.Node.to_global_id(
- "Promotion", promotion_without_rules.id
+ "Promotion", catalogue_promotion_without_rules.id
)
assert line.unit_discount_amount == reward_value
assert line.unit_discount_value == reward_value
@@ -637,7 +637,7 @@ def test_order_lines_create_variant_on_promotion(
assert discount.promotion_rule == rule
assert discount.amount_value == reward_value
assert discount.type == DiscountType.PROMOTION
- assert discount.name == f"{promotion_without_rules.name}: {rule.name}"
+ assert discount.name == f"{catalogue_promotion_without_rules.name}: {rule.name}"
assert (
discount.translated_name
== f"{promotion_translation_fr.name}: {promotion_rule_translation_fr.name}"
diff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.py
index c9b593c64f..2bcedef2f3 100644
--- a/saleor/graphql/product/tests/test_variant_pricing.py
+++ b/saleor/graphql/product/tests/test_variant_pricing.py
@@ -56,12 +56,12 @@ query ($channel: String, $address: AddressInput) {
def test_get_variant_pricing_on_promotion(
- api_client, promotion_with_single_rule, product, channel_USD
+ api_client, catalogue_promotion_with_single_rule, product, channel_USD
):
# given
variant_listing = product.variants.first().channel_listings.get()
price = variant_listing.price
- promotion = promotion_with_single_rule
+ promotion = catalogue_promotion_with_single_rule
rule = promotion.rules.first()
discounted_value = rule.reward_value
discounted_price = price.amount - discounted_value
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 80844e521e..f8f9b3f425 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -12716,6 +12716,7 @@ enum OrderDiscountType @doc(category: "Discounts") {
VOUCHER
MANUAL
PROMOTION
+ ORDER_PROMOTION
}
type OrderError @doc(category: "Orders") {
@@ -14213,6 +14214,15 @@ type Promotion implements Node & ObjectWithMetadata @doc(category: "Discounts")
"""Name of the promotion."""
name: String!
+ """
+ The type of the promotion. Implicate if the discount is applied on catalogue or order level.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ type: PromotionTypeEnum
+
"""Description of the promotion."""
description: JSON
@@ -14241,6 +14251,12 @@ type Promotion implements Node & ObjectWithMetadata @doc(category: "Discounts")
events: [PromotionEvent!]
}
+"""An enumeration."""
+enum PromotionTypeEnum @doc(category: "Discounts") {
+ CATALOGUE
+ ORDER
+}
+
"""
Represents the promotion rule that specifies the conditions that must be met to apply the promotion discount.
@@ -14267,16 +14283,47 @@ type PromotionRule implements Node @doc(category: "Discounts") {
"""
channels: [Channel!]
+ """
+ The reward value of the promotion rule. Defines the discount value applied when the rule conditions are met.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ rewardValue: PositiveDecimal
+
"""The type of reward value of the promotion rule."""
rewardValueType: RewardValueTypeEnum
+ """
+ The type of the predicate that must be met to apply the reward.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ predicateType: PromotionTypeEnum
+
"""The catalogue predicate that must be met to apply the rule reward."""
cataloguePredicate: JSON
"""
- The reward value of the promotion rule. Defines the discount value applied when the rule conditions are met.
+ The checkout/order predicate that must be met to apply the rule reward.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
- rewardValue: PositiveDecimal
+ orderPredicate: JSON
+
+ """
+ The reward type of the promotion rule.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ rewardType: RewardTypeEnum
"""Returns translated promotion rule fields for the given language code."""
translation(
@@ -14291,6 +14338,11 @@ enum RewardValueTypeEnum @doc(category: "Discounts") {
PERCENTAGE
}
+"""An enumeration."""
+enum RewardTypeEnum @doc(category: "Discounts") {
+ SUBTOTAL_DISCOUNT
+}
+
union PromotionEvent = PromotionCreatedEvent | PromotionUpdatedEvent | PromotionStartedEvent | PromotionEndedEvent | PromotionRuleCreatedEvent | PromotionRuleUpdatedEvent | PromotionRuleDeletedEvent
"""
@@ -14540,6 +14592,7 @@ input PromotionWhereInput @doc(category: "Discounts") {
"""Filter promotions by start date."""
startDate: DateTimeFilterInput
isOldSale: Boolean
+ type: PromotionTypeEnumFilterInput
"""List of conditions that must be met."""
AND: [PromotionWhereInput!]
@@ -14548,6 +14601,14 @@ input PromotionWhereInput @doc(category: "Discounts") {
OR: [PromotionWhereInput!]
}
+input PromotionTypeEnumFilterInput @doc(category: "Discounts") {
+ """The value equal to."""
+ eq: PromotionTypeEnum
+
+ """The value included in."""
+ oneOf: [PromotionTypeEnum!]
+}
+
input PromotionSortingInput @doc(category: "Discounts") {
"""Specifies the direction in which to sort promotions."""
direction: OrderDirection!
@@ -27397,6 +27458,12 @@ type PromotionCreateError {
"""Index of an input list item that caused the error."""
index: Int
+
+ """Limit of rules with orderPredicate defined."""
+ rulesLimit: Int
+
+ """Number of rules with orderPredicate defined exceeding the limit."""
+ exceedBy: Int
}
"""An enumeration."""
@@ -27407,6 +27474,8 @@ enum PromotionCreateErrorCode {
INVALID
MULTIPLE_CURRENCIES_NOT_ALLOWED
INVALID_PRECISION
+ MISSING_CHANNELS
+ RULES_NUMBER_LIMIT
}
input PromotionCreateInput @doc(category: "Discounts") {
@@ -27422,6 +27491,17 @@ input PromotionCreateInput @doc(category: "Discounts") {
"""Promotion name."""
name: String!
+ """
+ Defines the promotion type. Implicate the required promotion rules predicate type and whether the promotion rules will give the catalogue or order discount.
+
+ The default value is `Catalogue`.
+
+ This field will be required from Saleor 3.20.
+
+ Added in Saleor 3.19.
+ """
+ type: PromotionTypeEnum
+
"""List of promotion rules."""
rules: [PromotionRuleInput!]
}
@@ -27438,6 +27518,15 @@ input PromotionRuleInput @doc(category: "Discounts") {
"""
cataloguePredicate: CataloguePredicateInput
+ """
+ Defines the conditions on the checkout/draft order level that must be met for the reward to be applied.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ orderPredicate: OrderPredicateInput
+
"""
Defines the promotion rule reward value type. Must be provided together with reward value.
"""
@@ -27448,6 +27537,15 @@ input PromotionRuleInput @doc(category: "Discounts") {
"""
rewardValue: PositiveDecimal
+ """
+ Defines the reward type of the promotion rule.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ rewardType: RewardTypeEnum
+
"""List of channel ids to which the rule should apply to."""
channels: [ID!]
}
@@ -27472,6 +27570,31 @@ input CataloguePredicateInput @doc(category: "Discounts") {
OR: [CataloguePredicateInput!]
}
+input OrderPredicateInput @doc(category: "Discounts") {
+ """Defines the conditions related to checkout and order objects."""
+ discountedObjectPredicate: DiscountedObjectWhereInput
+
+ """List of conditions that must be met."""
+ AND: [OrderPredicateInput!]
+
+ """A list of conditions of which at least one must be met."""
+ OR: [OrderPredicateInput!]
+}
+
+input DiscountedObjectWhereInput @doc(category: "Discounts") {
+ """Filter by the base subtotal price."""
+ baseSubtotalPrice: DecimalFilterInput
+
+ """Filter by the base total price."""
+ baseTotalPrice: DecimalFilterInput
+
+ """List of conditions that must be met."""
+ AND: [DiscountedObjectWhereInput!]
+
+ """A list of conditions of which at least one must be met."""
+ OR: [DiscountedObjectWhereInput!]
+}
+
"""
Updates an existing promotion.
@@ -27590,6 +27713,12 @@ type PromotionRuleCreateError {
"""The error code."""
code: PromotionRuleCreateErrorCode!
+
+ """Limit of rules with orderPredicate defined."""
+ rulesLimit: Int
+
+ """Number of rules with orderPredicate defined exceeding the limit."""
+ exceedBy: Int
}
"""An enumeration."""
@@ -27600,6 +27729,8 @@ enum PromotionRuleCreateErrorCode {
INVALID
MULTIPLE_CURRENCIES_NOT_ALLOWED
INVALID_PRECISION
+ MISSING_CHANNELS
+ RULES_NUMBER_LIMIT
}
input PromotionRuleCreateInput {
@@ -27614,6 +27745,15 @@ input PromotionRuleCreateInput {
"""
cataloguePredicate: CataloguePredicateInput
+ """
+ Defines the conditions on the checkout/draft order level that must be met for the reward to be applied.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ orderPredicate: OrderPredicateInput
+
"""
Defines the promotion rule reward value type. Must be provided together with reward value.
"""
@@ -27624,6 +27764,15 @@ input PromotionRuleCreateInput {
"""
rewardValue: PositiveDecimal
+ """
+ Defines the reward type of the promotion rule.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ rewardType: RewardTypeEnum
+
"""List of channel ids to which the rule should apply to."""
channels: [ID!]
@@ -27669,6 +27818,7 @@ enum PromotionRuleUpdateErrorCode {
GRAPHQL_ERROR
NOT_FOUND
INVALID
+ REQUIRED
DUPLICATED_INPUT_ITEM
MISSING_CHANNELS
MULTIPLE_CURRENCIES_NOT_ALLOWED
@@ -27687,6 +27837,15 @@ input PromotionRuleUpdateInput {
"""
cataloguePredicate: CataloguePredicateInput
+ """
+ Defines the conditions on the checkout/draft order level that must be met for the reward to be applied.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ orderPredicate: OrderPredicateInput
+
"""
Defines the promotion rule reward value type. Must be provided together with reward value.
"""
@@ -27697,6 +27856,15 @@ input PromotionRuleUpdateInput {
"""
rewardValue: PositiveDecimal
+ """
+ Defines the reward type of the promotion rule.
+
+ Added in Saleor 3.19.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ rewardType: RewardTypeEnum
+
"""List of channel ids to add."""
addChannels: [ID!]
diff --git a/saleor/graphql/translations/tests/mutations/test_promotion_translate.py b/saleor/graphql/translations/tests/mutations/test_promotion_translate.py
index 56d10f370c..728b044956 100644
--- a/saleor/graphql/translations/tests/mutations/test_promotion_translate.py
+++ b/saleor/graphql/translations/tests/mutations/test_promotion_translate.py
@@ -47,12 +47,13 @@ def test_promotion_create_translation(
mocked_get_webhooks_for_event,
any_webhook,
staff_api_client,
- promotion,
+ catalogue_promotion,
permission_manage_translations,
settings,
description_json,
):
# given
+ promotion = catalogue_promotion
mocked_get_webhooks_for_event.return_value = [any_webhook]
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
@@ -98,11 +99,12 @@ def test_promotion_create_translation(
def test_promotion_update_translation(
staff_api_client,
- promotion,
+ catalogue_promotion,
promotion_translation_fr,
permission_manage_translations,
):
# given
+ promotion = catalogue_promotion
assert promotion.translations.first().name == "French promotion name"
promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
updated_name = "Updated French promotion name."
@@ -135,9 +137,10 @@ def test_promotion_update_translation(
def test_promotion_create_translation_no_permission(
staff_api_client,
- promotion,
+ catalogue_promotion,
):
# given
+ promotion = catalogue_promotion
promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
variables = {
@@ -160,10 +163,11 @@ def test_promotion_create_translation_no_permission(
def test_promotion_create_translation_by_translatable_content_id(
staff_api_client,
- promotion,
+ catalogue_promotion,
permission_manage_translations,
):
# given
+ promotion = catalogue_promotion
translatable_content_id = graphene.Node.to_global_id(
"PromotionTranslatableContent", promotion.id
)
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index 617ecbe9b9..5b6d6548be 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -3103,7 +3103,7 @@ def test_translations_query(
product,
published_collection,
voucher,
- promotion,
+ catalogue_promotion,
shipping_method,
page,
menu_item,
@@ -4243,11 +4243,12 @@ QUERY_TRANSLATION_PROMOTION = """
def test_translation_query_promotion(
staff_api_client,
- promotion,
+ catalogue_promotion,
promotion_translation_fr,
permission_manage_translations,
):
# given
+ promotion = catalogue_promotion
promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
variables = {
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 6551df9607..89c6ad9f3d 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -126,14 +126,14 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion(
order_with_lines,
product,
anonymous_plugins,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
):
# given
order = order_with_lines
variant = product.variants.first()
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [graphene.Node.to_global_id("Product", variant.product.id)]
@@ -165,7 +165,7 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
@@ -1388,14 +1388,14 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion_with_custom
order_with_lines,
product,
anonymous_plugins,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
):
# given
order = order_with_lines
variant = product.variants.first()
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
catalogue_predicate={
"productPredicate": {
"ids": [graphene.Node.to_global_id("Product", variant.product.id)]
@@ -1429,7 +1429,7 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion_with_custom
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 74ce1945ce..8dd9dec91b 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -265,13 +265,13 @@ def test_add_variant_to_order(
order,
customer_user,
variant,
- promotion_with_single_rule,
+ catalogue_promotion_with_single_rule,
):
# given
manager = get_plugins_manager(allow_replica=False)
quantity = 4
- promotion = promotion_with_single_rule
+ promotion = catalogue_promotion_with_single_rule
discount_value = promotion.rules.first().reward_value
channel_listing = variant.channel_listings.get(channel=order.channel)
channel_listing.discounted_price_amount = (
@@ -576,9 +576,13 @@ def test_get_order_country_use_channel_country(order):
def test_create_order_line_discounts(
- order_line, promotion, promotion_translation_fr, promotion_rule_translation_fr
+ 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]
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 864008c686..5fa2ea5227 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -334,6 +334,8 @@ def create_order_line_discounts(
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(
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 8aabaf4b06..641eea33c5 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -189,7 +189,7 @@ def test_get_channel_slug_from_payment_with_checkout(checkout_with_payments):
assert get_channel_slug_from_payment(payment) == expected
-def test_get_channel_slug_from_payment_without_checkout_and_order(
+def test_get_channel_slug_from_payment_without_order(
checkout_with_payments,
):
payment = checkout_with_payments.payments.first()
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 58892e758d..27c0bbc659 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -294,6 +294,9 @@ def generate_request_data_from_checkout_lines(
if voucher and not voucher.apply_once_per_order
else False
)
+ applicable_checkout_discount = (
+ bool(checkout_info.discounts) or is_entire_order_discount
+ )
for line_info in lines_info:
product = line_info.product
@@ -302,9 +305,9 @@ def generate_request_data_from_checkout_lines(
tax_override_data = {}
if not charge_taxes:
- if not is_entire_order_discount:
+ if not applicable_checkout_discount:
continue
- # if there is a voucher for the entire order we need to attach this line
+ # if there is a checkout discount we need to attach this line
# with 0 tax to propagate discount through all lines
tax_override_data = {
"type": "taxAmount",
@@ -339,7 +342,7 @@ def generate_request_data_from_checkout_lines(
"item_code": item_code,
"name": name,
"prices_entered_with_tax": prices_entered_with_tax,
- "discounted": is_entire_order_discount,
+ "discounted": applicable_checkout_discount,
"tax_override_data": tax_override_data,
}
@@ -511,26 +514,7 @@ def generate_request_data_from_checkout(
if not lines:
return {}
- discount_amount = Decimal("0")
- if voucher := checkout_info.voucher:
- # for apply_once_per_order vouchers the discount is already applied on lines
- applicable_discount = (
- voucher.type != VoucherType.SPECIFIC_PRODUCT
- and not voucher.apply_once_per_order
- )
-
- if voucher.type == VoucherType.SHIPPING:
- # when the taxes are not calculated on shipping method, the shipping
- # discount cannot by applied by plugin
- applicable_discount = applicable_discount and SHIPPING_ITEM_CODE in {
- line["itemCode"] for line in lines
- }
-
- discount_amount = (
- checkout_info.checkout.discount.amount
- if applicable_discount
- else Decimal("0")
- )
+ discount_amount = _get_checkout_discount_amount(checkout_info, lines)
currency = checkout_info.checkout.currency
customer_email = cast(str, checkout_info.get_customer_email())
@@ -547,6 +531,37 @@ def generate_request_data_from_checkout(
return data
+def _get_checkout_discount_amount(checkout_info, lines):
+ """Return the discount amount for the checkout.
+
+ Return the discount amount from the entire order or shipping voucher, or from
+ order promotion discount if there is no voucher and any promotion is eligible.
+ """
+ discount_amount = Decimal("0")
+ if (voucher := checkout_info.voucher) or checkout_info.discounts:
+ # for apply_once_per_order vouchers the discount is already applied on lines
+ applicable_discount = True
+ if voucher:
+ applicable_discount = (
+ voucher.type != VoucherType.SPECIFIC_PRODUCT
+ and not voucher.apply_once_per_order
+ )
+
+ if voucher.type == VoucherType.SHIPPING:
+ # when the taxes are not calculated on shipping method, the shipping
+ # discount cannot by applied by plugin
+ applicable_discount = applicable_discount and SHIPPING_ITEM_CODE in {
+ line["itemCode"] for line in lines
+ }
+
+ discount_amount = (
+ checkout_info.checkout.discount_amount
+ if applicable_discount
+ else Decimal("0")
+ )
+ return discount_amount
+
+
def _fetch_new_taxes_data(
data: dict[str, dict], data_cache_key: str, config: AvataxConfiguration
):
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_with_order_promotion[20.33-25.00-True].yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_with_order_promotion[20.33-25.00-True].yaml
new file mode 100644
index 0000000000..a8d487ab0a
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_with_order_promotion[20.33-25.00-True].yaml
@@ -0,0 +1,74 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "123", "discounted": true, "description": "Test product",
+ "ref1": "123"}, {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded":
+ true, "itemCode": "Shipping", "discounted": false, "description": null}], "code":
+ "dbb271fe-8d7c-4620-8350-eff0ad235400", "date": "2024-01-04", "customerCode":
+ 0, "discount": "5", "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":
+ "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},
+ "shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
+ "region": "", "country": "PL", "postalCode": "53-105"}}, "commit": false, "currencyCode":
+ "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '842'
+ User-Agent:
+ - Saleor/3.19
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":0,"code":"dbb271fe-8d7c-4620-8350-eff0ad235400","companyId":7799660,"date":"2024-01-04","paymentDate":"2024-01-04","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":33.46,"totalExempt":0.0,"totalDiscount":5.0,"totalTax":6.54,"totalTaxable":28.46,"totalTaxCalculated":6.54,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-01-04","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-01-04T14:12:41.2952875Z","modifiedUserId":6479978,"taxDate":"2024-01-04","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
+ product","discountAmount":5.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":25.3300,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-01-04","tax":4.67,"taxableAmount":20.33,"taxCalculated":4.67,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-04","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":4.67,"taxableAmount":20.33,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":4.67,"rateType":"Standard","rateTypeCode":"S","taxableUnits":20.3300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":20.33,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":4.67,"reportingTaxCalculated":4.67,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-01-04","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-01-04","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":1.87,"taxableAmount":8.13,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":1.87,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Olawska
+ 10","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-105","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":28.46,"rate":0.230000,"tax":6.54,"taxCalculated":6.54,"nonTaxable":0.0,"exemption":0.0}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 04 Jan 2024 14:12:41 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/0
+ ServerDuration:
+ - '00:00:00.0230056'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 8e27e79d-5619-429d-ae75-f8c4e8dbf2f9
+ x-correlation-id:
+ - 8e27e79d-5619-429d-ae75-f8c4e8dbf2f9
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_with_order_promotion[25.00-30.75-False].yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_with_order_promotion[25.00-30.75-False].yaml
new file mode 100644
index 0000000000..634d57741f
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_with_order_promotion[25.00-30.75-False].yaml
@@ -0,0 +1,74 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ false, "itemCode": "123", "discounted": true, "description": "Test product",
+ "ref1": "123"}, {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded":
+ false, "itemCode": "Shipping", "discounted": false, "description": null}], "code":
+ "08364741-1d31-48da-a829-5bb0d48ae572", "date": "2024-01-04", "customerCode":
+ 0, "discount": "5", "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":
+ "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},
+ "shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
+ "region": "", "country": "PL", "postalCode": "53-105"}}, "commit": false, "currencyCode":
+ "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '844'
+ User-Agent:
+ - Saleor/3.19
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":0,"code":"08364741-1d31-48da-a829-5bb0d48ae572","companyId":7799660,"date":"2024-01-04","paymentDate":"2024-01-04","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":40.0,"totalExempt":0.0,"totalDiscount":5.0,"totalTax":8.05,"totalTaxable":35.0,"totalTaxCalculated":8.05,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-01-04","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-01-04T14:12:42.7358334Z","modifiedUserId":6479978,"taxDate":"2024-01-04","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
+ product","discountAmount":5.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":30.0,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-01-04","tax":5.75,"taxableAmount":25.0,"taxCalculated":5.75,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-04","taxIncluded":false,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":5.75,"taxableAmount":25.0,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":5.75,"rateType":"Standard","rateTypeCode":"S","taxableUnits":25.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":25.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":5.75,"reportingTaxCalculated":5.75,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":10.0,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-01-04","tax":2.3,"taxableAmount":10.0,"taxCalculated":2.3,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-01-04","taxIncluded":false,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":2.3,"taxableAmount":10.0,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":2.3,"rateType":"Standard","rateTypeCode":"S","taxableUnits":10.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":10.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":2.3,"reportingTaxCalculated":2.3,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Olawska
+ 10","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-105","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":35.0,"rate":0.230000,"tax":8.05,"taxCalculated":8.05,"nonTaxable":0.0,"exemption":0.0}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 04 Jan 2024 14:12:42 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/0
+ ServerDuration:
+ - '00:00:00.0171537'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 3ce8fda1-36f4-472a-ba1e-6884a14f172e
+ x-correlation-id:
+ - 3ce8fda1-36f4-472a-ba1e-6884a14f172e
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_order_promotion_charge_taxes.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_order_promotion_charge_taxes.yaml
new file mode 100644
index 0000000000..7cb5b526ca
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_order_promotion_charge_taxes.yaml
@@ -0,0 +1,74 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "123", "discounted": true, "description": "Test product",
+ "ref1": "123"}, {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded":
+ true, "itemCode": "Shipping", "discounted": false, "description": null}], "code":
+ "04d40c20-5a6a-4bf5-8f0a-1ad372cc78aa", "date": "2024-01-04", "customerCode":
+ 0, "discount": "5", "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":
+ "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},
+ "shipTo": {"line1": "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region":
+ "", "country": "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode":
+ "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '841'
+ User-Agent:
+ - Saleor/3.19
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":0,"code":"04d40c20-5a6a-4bf5-8f0a-1ad372cc78aa","companyId":7799660,"date":"2024-01-04","paymentDate":"2024-01-04","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":33.46,"totalExempt":0.0,"totalDiscount":5.0,"totalTax":6.54,"totalTaxable":28.46,"totalTaxCalculated":6.54,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-01-04","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-01-04T14:36:39.279923Z","modifiedUserId":6479978,"taxDate":"2024-01-04","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
+ product","discountAmount":5.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":25.3300,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-01-04","tax":4.67,"taxableAmount":20.33,"taxCalculated":4.67,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-04","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":4.67,"taxableAmount":20.33,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":4.67,"rateType":"Standard","rateTypeCode":"S","taxableUnits":20.3300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":20.33,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":4.67,"reportingTaxCalculated":4.67,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-01-04","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-01-04","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":1.87,"taxableAmount":8.13,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":1.87,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":28.46,"rate":0.230000,"tax":6.54,"taxCalculated":6.54,"nonTaxable":0.0,"exemption":0.0}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 04 Jan 2024 14:36:39 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/0
+ ServerDuration:
+ - '00:00:00.0177465'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 11e60e28-5850-4ee3-9990-32a921a5a7a9
+ x-correlation-id:
+ - 11e60e28-5850-4ee3-9990-32a921a5a7a9
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_with_order_promotion.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_with_order_promotion.yaml
new file mode 100644
index 0000000000..149a55ff06
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_with_order_promotion.yaml
@@ -0,0 +1,74 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "PS081282", "taxIncluded":
+ true, "itemCode": "123", "discounted": true, "description": "Test product",
+ "ref1": "123"}, {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded":
+ true, "itemCode": "Shipping", "discounted": false, "description": null}], "code":
+ "478cce26-4067-48f5-90cb-95ee3ab8f827", "date": "2024-01-05", "customerCode":
+ 0, "discount": "5", "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":
+ "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},
+ "shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
+ "region": "", "country": "PL", "postalCode": "53-105"}}, "commit": false, "currencyCode":
+ "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '842'
+ User-Agent:
+ - Saleor/3.19
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":0,"code":"478cce26-4067-48f5-90cb-95ee3ab8f827","companyId":7799660,"date":"2024-01-05","paymentDate":"2024-01-05","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":33.46,"totalExempt":0.0,"totalDiscount":5.0,"totalTax":6.54,"totalTaxable":28.46,"totalTaxCalculated":6.54,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-01-05","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-01-05T08:43:29.2600157Z","modifiedUserId":6479978,"taxDate":"2024-01-05","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
+ product","discountAmount":5.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":25.3300,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-01-05","tax":4.67,"taxableAmount":20.33,"taxCalculated":4.67,"taxCode":"PS081282","taxCodeId":38007,"taxDate":"2024-01-05","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":4.67,"taxableAmount":20.33,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":4.67,"rateType":"Standard","rateTypeCode":"S","taxableUnits":20.3300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":20.33,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":4.67,"reportingTaxCalculated":4.67,"avtUserBIN":"","liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLSL230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-01-05","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-01-05","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":1.87,"taxableAmount":8.13,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":1.87,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Olawska
+ 10","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-105","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":28.46,"rate":0.230000,"tax":6.54,"taxCalculated":6.54,"nonTaxable":0.0,"exemption":0.0}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Fri, 05 Jan 2024 08:43:29 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/0
+ ServerDuration:
+ - '00:00:00.0216793'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 5867b216-b722-4e4a-a6fb-b2e8deff7493
+ x-correlation-id:
+ - 5867b216-b722-4e4a-a6fb-b2e8deff7493
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.py
index aa9a6558f6..e964fe4e91 100644
--- a/saleor/plugins/avatax/tests/conftest.py
+++ b/saleor/plugins/avatax/tests/conftest.py
@@ -122,6 +122,7 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):
tax_configuration=channel.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
return checkout_info
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index a054dd7f27..42de040035 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -235,6 +235,65 @@ def test_calculate_checkout_line_total_with_variant_on_promotion(
)
+ ("expected_net", "expected_gross", "prices_entered_with_tax"),
+ [
+ ("20.33", "25.00", True),
+ ("25.00", "30.75", False),
+ ],
+)
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_checkout_line_total_with_order_promotion(
+ expected_net,
+ expected_gross,
+ prices_entered_with_tax,
+ checkout_with_item_and_order_discount,
+ ship_to_pl_address,
+ monkeypatch,
+ shipping_zone,
+ plugin_configuration,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ plugin_configuration()
+ manager = get_plugins_manager(allow_replica=False)
+
+ checkout.shipping_address = ship_to_pl_address
+ checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.save()
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.charge_taxes = True
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ line = checkout.lines.first()
+ product = line.variant.product
+ product.metadata = {}
+ product.save()
+ product.product_type.save()
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_line_info = lines[0]
+
+ # when
+ total = manager.calculate_checkout_line_total(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ checkout.shipping_address,
+ )
+
+ # then
+ total = quantize_price(total, total.currency)
+ assert total == TaxedMoney(
+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
+ )
+
+
@pytest.mark.vcr
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
def test_calculate_checkout_line_total_with_voucher(
@@ -1293,6 +1352,69 @@ def test_calculate_checkout_total(
)
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_checkout_total_with_order_promotion(
+ checkout_with_item_and_order_discount,
+ shipping_zone,
+ ship_to_pl_address,
+ monkeypatch,
+ plugin_configuration,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ discount_amount = checkout.discount_amount
+
+ plugin_configuration()
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
+ lambda _: {"PS081282": "desc", TAX_CODE_NON_TAXABLE_PRODUCT: "desc"},
+ )
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.AvataxPlugin._skip_plugin", lambda *_: False
+ )
+ manager = get_plugins_manager(allow_replica=False)
+ checkout.shipping_address = ship_to_pl_address
+ checkout.save()
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = True
+ tax_configuration.charge_taxes = True
+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ shipping_method = shipping_zone.shipping_methods.get()
+ checkout.shipping_method = shipping_method
+ checkout.save(update_fields=["shipping_method"])
+
+ line = checkout.lines.first()
+ product = line.variant.product
+
+ manager.assign_tax_code_to_object_meta(product.tax_class, "PS081282")
+ product.save()
+ product.tax_class.save()
+
+ checkout_info = fetch_checkout_info(checkout, [], manager)
+ lines, _ = fetch_checkout_lines(checkout)
+
+ # when
+ total = manager.calculate_checkout_total(checkout_info, lines, ship_to_pl_address)
+
+ # then
+ total = quantize_price(total, total.currency)
+ line_info = lines[0]
+ unit_price = line_info.variant.get_price(line_info.channel_listing)
+ subtotal_price_amount = (unit_price * line.quantity).amount - discount_amount
+ shipping_price = shipping_method.channel_listings.get(
+ channel=checkout.channel
+ ).price
+ total_price_amount = subtotal_price_amount + shipping_price.amount
+ assert total == TaxedMoney(
+ net=Money(round(total_price_amount / Decimal("1.23"), 2), checkout.currency),
+ gross=Money(total_price_amount, "USD"),
+ )
+
+
@pytest.mark.vcr
@pytest.mark.parametrize(
("expected_net", "expected_gross", "voucher_amount", "prices_entered_with_tax"),
@@ -2002,7 +2124,7 @@ def test_calculate_checkout_subtotal_with_promotion(
update_discounted_prices_for_promotion(Product.objects.all())
lines, _ = fetch_checkout_lines(checkout)
- create_or_update_discount_objects_from_promotion_for_checkout(lines)
+ create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)
# when
total = manager.calculate_checkout_subtotal(checkout_info, lines, address)
@@ -2753,6 +2875,112 @@ def test_calculate_checkout_line_unit_price_with_variant_on_promotion(
)
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_checkout_line_unit_price_order_promotion_charge_taxes(
+ checkout_with_item_and_order_discount,
+ shipping_zone,
+ address,
+ plugin_configuration,
+):
+ # given
+ plugin_configuration()
+ checkout = checkout_with_item_and_order_discount
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_line = lines[0]
+ discount_amount = checkout.discount_amount
+
+ manager = get_plugins_manager(allow_replica=False)
+
+ method = shipping_zone.shipping_methods.get()
+ checkout.shipping_address = address
+ checkout.shipping_method_name = method.name
+ checkout.shipping_method = method
+ checkout.save()
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = True
+ tax_configuration.charge_taxes = True
+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ line_price = manager.calculate_checkout_line_unit_price(
+ checkout_info,
+ lines,
+ checkout_line,
+ checkout.shipping_address,
+ )
+
+ # then
+ line = lines[0].line
+ unit_price = checkout_line.variant.get_price(checkout_line.channel_listing)
+ total_price_amount = (unit_price * line.quantity).amount - discount_amount
+ discounted_unit_amount = total_price_amount / line.quantity
+ expected_line_price = TaxedMoney(
+ net=Money(
+ round(discounted_unit_amount / Decimal("1.23"), 2), checkout.currency
+ ),
+ gross=Money(round(discounted_unit_amount, 2), checkout.currency),
+ )
+ assert line_price == expected_line_price
+
+
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_checkout_line_unit_price_checkout_promotion_do_not_charge_taxes(
+ checkout_with_item_and_order_discount,
+ shipping_zone,
+ address,
+ plugin_configuration,
+):
+ # given
+ plugin_configuration()
+ checkout = checkout_with_item_and_order_discount
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_line = lines[0]
+ discount_amount = checkout.discount_amount
+
+ manager = get_plugins_manager(allow_replica=False)
+
+ method = shipping_zone.shipping_methods.get()
+ checkout.shipping_address = address
+ checkout.shipping_method_name = method.name
+ checkout.shipping_method = method
+ checkout.save()
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = True
+ tax_configuration.charge_taxes = False
+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ line_price = manager.calculate_checkout_line_unit_price(
+ checkout_info,
+ lines,
+ checkout_line,
+ checkout.shipping_address,
+ )
+
+ # then
+ line = lines[0].line
+ unit_price = checkout_line.variant.get_price(checkout_line.channel_listing)
+ total_price_amount = (unit_price * line.quantity).amount - discount_amount
+ discounted_unit_amount = round(total_price_amount / line.quantity, 2)
+ expected_line_price = TaxedMoney(
+ net=Money(discounted_unit_amount, checkout.currency),
+ gross=Money(discounted_unit_amount, checkout.currency),
+ )
+ assert line_price == expected_line_price
+
+
@pytest.mark.vcr
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
def test_calculate_checkout_line_unit_price_with_voucher(
@@ -3367,6 +3595,7 @@ def test_get_checkout_line_tax_rate(
tax_configuration=checkout_with_item.channel.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_line_info = lines[0]
@@ -3432,6 +3661,7 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(
tax_configuration=checkout_with_item.channel.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_line_info = lines[0]
@@ -3506,6 +3736,7 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
tax_configuration=checkout_with_item.channel.tax_configuration,
valid_pick_up_points=[],
all_shipping_methods=[],
+ discounts=[],
)
add_variant_to_checkout(checkout_info, variant2, 1)
@@ -4873,7 +5104,10 @@ def test_get_order_request_data_draft_order_shipping_voucher_amount_too_high(
def test_get_order_request_data_draft_order_on_promotion(
- order_line_on_promotion, shipping_zone, promotion_with_single_rule, avatax_config
+ order_line_on_promotion,
+ shipping_zone,
+ catalogue_promotion_with_single_rule,
+ avatax_config,
):
# given
order = order_line_on_promotion.order
@@ -4890,7 +5124,7 @@ def test_get_order_request_data_draft_order_on_promotion(
variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.id)
predicate = {"variantPredicate": {"ids": [variant_id]}}
- rule = promotion_with_single_rule.rules.first()
+ rule = catalogue_promotion_with_single_rule.rules.first()
rule.catalogue_predicate = predicate
rule.save(update_fields=["catalogue_predicate"])
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 810252cf69..c30ca19099 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -398,7 +398,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info,
checkout_info.channel,
)
- # apply entire order discount
+ # apply entire order discount or discount from order promotion
default_value = base_calculations.apply_checkout_discount_on_checkout_line(
checkout_info,
lines,
@@ -466,7 +466,7 @@ class PluginsManager(PaymentInterface):
default_value * quantity,
)
default_taxed_value = TaxedMoney(
- net=total_value / quantity, gross=default_value
+ net=total_value / quantity, gross=total_value / quantity
)
unit_price = self.__run_method_on_plugins(
"calculate_checkout_line_unit_price",
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index 728202de0e..54de2b2eca 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -1669,14 +1669,17 @@ def test_sale_toggle(promotion_converted_from_sale, subscription_sale_toggle_web
assert deliveries[0].webhook == webhooks[0]
-def test_promotion_created(promotion, subscription_promotion_created_webhook):
+def test_promotion_created(catalogue_promotion, subscription_promotion_created_webhook):
# given
+ promotion = catalogue_promotion
webhooks = [subscription_promotion_created_webhook]
event_type = WebhookEventAsyncType.PROMOTION_CREATED
expected_payload = generate_promotion_payload(promotion)
# when
- deliveries = create_deliveries_for_subscriptions(event_type, promotion, webhooks)
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, catalogue_promotion, webhooks
+ )
# then
assert deliveries[0].payload.payload == json.dumps(expected_payload)
@@ -1684,8 +1687,9 @@ def test_promotion_created(promotion, subscription_promotion_created_webhook):
assert deliveries[0].webhook == webhooks[0]
-def test_promotion_updated(promotion, subscription_promotion_updated_webhook):
+def test_promotion_updated(catalogue_promotion, subscription_promotion_updated_webhook):
# given
+ promotion = catalogue_promotion
webhooks = [subscription_promotion_updated_webhook]
event_type = WebhookEventAsyncType.PROMOTION_UPDATED
expected_payload = generate_promotion_payload(promotion)
@@ -1699,8 +1703,9 @@ def test_promotion_updated(promotion, subscription_promotion_updated_webhook):
assert deliveries[0].webhook == webhooks[0]
-def test_promotion_deleted(promotion, subscription_promotion_deleted_webhook):
+def test_promotion_deleted(catalogue_promotion, subscription_promotion_deleted_webhook):
# given
+ promotion = catalogue_promotion
webhooks = [subscription_promotion_deleted_webhook]
event_type = WebhookEventAsyncType.PROMOTION_DELETED
expected_payload = generate_promotion_payload(promotion)
@@ -1714,8 +1719,9 @@ def test_promotion_deleted(promotion, subscription_promotion_deleted_webhook):
assert deliveries[0].webhook == webhooks[0]
-def test_promotion_started(promotion, subscription_promotion_started_webhook):
+def test_promotion_started(catalogue_promotion, subscription_promotion_started_webhook):
# given
+ promotion = catalogue_promotion
webhooks = [subscription_promotion_started_webhook]
event_type = WebhookEventAsyncType.PROMOTION_STARTED
expected_payload = generate_promotion_payload(promotion)
@@ -1729,8 +1735,9 @@ def test_promotion_started(promotion, subscription_promotion_started_webhook):
assert deliveries[0].webhook == webhooks[0]
-def test_promotion_ended(promotion, subscription_promotion_ended_webhook):
+def test_promotion_ended(catalogue_promotion, subscription_promotion_ended_webhook):
# given
+ promotion = catalogue_promotion
webhooks = [subscription_promotion_ended_webhook]
event_type = WebhookEventAsyncType.PROMOTION_ENDED
expected_payload = generate_promotion_payload(promotion)
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index d13c61b913..b74c3aae24 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -26,13 +26,13 @@ from ....account.notifications import (
send_account_confirmation,
)
from ....app.models import App
-from ....checkout.fetch import fetch_checkout_lines
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ....core.notification.utils import get_site_context
from ....core.notify_events import NotifyEventType
from ....core.utils.url import prepare_url
-from ....discount import RewardValueType
+from ....discount import RewardType, RewardValueType
from ....discount.interface import VariantPromotionRuleInfo
from ....discount.utils import (
create_or_update_discount_objects_from_promotion_for_checkout,
@@ -1054,17 +1054,19 @@ def test_checkout_created(
def test_checkout_payload_includes_promotions(
- checkout_with_item, promotion_without_rules
+ checkout_with_item, catalogue_promotion_without_rules
):
# given
checkout = checkout_with_item
checkout_lines, _ = fetch_checkout_lines(checkout, prefetch_variant_attributes=True)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
variant = checkout_lines[0].variant
channel_listing = variant.channel_listings.first()
reward_value = Decimal("5")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"productPredicate": {
@@ -1091,13 +1093,15 @@ def test_checkout_payload_includes_promotions(
VariantPromotionRuleInfo(
rule=rule,
variant_listing_promotion_rule=listing_promotion_rule,
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
promotion_translation=None,
rule_translation=None,
)
]
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines
+ )
variant_price_with_sale = variant.get_price(
channel_listing=channel_listing,
@@ -1114,6 +1118,59 @@ def test_checkout_payload_includes_promotions(
assert Decimal(data[0]["lines"][0]["base_price"]) == variant_price_with_sale.amount
+def test_checkout_payload_includes_order_promotion_discount(
+ checkout_with_item, catalogue_promotion_without_rules
+):
+ # given
+ checkout = checkout_with_item
+ checkout_lines, _ = fetch_checkout_lines(checkout, prefetch_variant_attributes=True)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
+
+ variant = checkout_lines[0].variant
+ channel_listing = variant.channel_listings.first()
+
+ reward_value = Decimal("5")
+ rule = catalogue_promotion_without_rules.rules.create(
+ name="Fixed promotion rule",
+ order_predicate={
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {
+ "range": {
+ "gte": 20,
+ }
+ }
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel_listing.channel)
+
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines
+ )
+ checkout.save(
+ update_fields=[
+ "discount_amount",
+ "discount_name",
+ "translated_discount_name",
+ ]
+ )
+
+ # when
+ data = json.loads(generate_checkout_payload(checkout))
+
+ # then
+ variant_price = variant.get_price(
+ channel_listing=channel_listing,
+ )
+ assert Decimal(data[0]["discount_amount"]) == reward_value
+ assert data[0]["discount_name"] == checkout.discount_name
+ assert Decimal(data[0]["lines"][0]["base_price"]) == variant_price.amount
+
+
@freeze_time("1914-06-28 10:50")
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index 970e3af37b..a7e5401ac2 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -12,6 +12,7 @@ from django.utils import timezone
from ..attribute.models import Attribute
from ..celeryconf import app
from ..core.exceptions import PreorderAllocationError
+from ..discount import PromotionType
from ..discount.models import Promotion, PromotionRule
from ..discount.utils import get_current_products_for_rules
from ..plugins.manager import get_plugins_manager
@@ -112,9 +113,11 @@ def update_products_discounted_prices_for_promotion_task(
Firstly the promotion rule variants are recalculated, then the products discounted
prices are calculated.
"""
- promotions = Promotion.objects.using(
- settings.DATABASE_CONNECTION_REPLICA_NAME
- ).active()
+ promotions = (
+ Promotion.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .active()
+ .filter(type=PromotionType.CATALOGUE)
+ )
kwargs = {"id__gt": start_id} if start_id else {}
if rule_ids:
kwargs["id__in"] = rule_ids # type: ignore[assignment]
@@ -122,9 +125,9 @@ def update_products_discounted_prices_for_promotion_task(
PromotionRule.objects.order_by("id")
.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
.filter(Exists(promotions.filter(id=OuterRef("promotion_id"))), **kwargs)
- .exclude(Q(reward_value__isnull=True) | Q(reward_value=0))[
- :PROMOTION_RULE_BATCH_SIZE
- ]
+ .exclude(
+ Q(reward_value__isnull=True) | Q(reward_value=0) | Q(catalogue_predicate={})
+ )[:PROMOTION_RULE_BATCH_SIZE]
)
if ids := list(rules.values_list("pk", flat=True)):
qs = PromotionRule.objects.filter(pk__in=ids).exclude(
diff --git a/saleor/product/tests/test_fetch_variants_for_promotion_rules.py b/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
index 698439fdb8..c0f24c7880 100644
--- a/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
+++ b/saleor/product/tests/test_fetch_variants_for_promotion_rules.py
@@ -10,7 +10,7 @@ from ..utils.variants import fetch_variants_for_promotion_rules
def test_fetch_variants_for_promotion_rules_discount(
- promotion_without_rules,
+ catalogue_promotion_without_rules,
product,
product_with_two_variants,
channel_USD,
@@ -18,7 +18,7 @@ def test_fetch_variants_for_promotion_rules_discount(
):
# given
variant = product.variants.first()
- promotion = promotion_without_rules
+ promotion = catalogue_promotion_without_rules
percentage_reward_value = Decimal("10")
reward_value = Decimal("2")
@@ -73,14 +73,37 @@ def test_fetch_variants_for_promotion_rules_discount(
)
+def test_fetch_variants_for_promotion_rules_empty_catalogue_predicate(
+ catalogue_promotion_without_rules, product, product_with_two_variants, channel_USD
+):
+ # given
+ promotion = catalogue_promotion_without_rules
+
+ percentage_reward_value = Decimal("10")
+ rule_1 = promotion.rules.create(
+ name="Percentage promotion rule",
+ catalogue_predicate={},
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=percentage_reward_value,
+ )
+ rule_1.channels.add(channel_USD)
+
+ # when
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # then
+ rule_1.refresh_from_db()
+ assert rule_1.variants.count() == 0
+
+
def test_fetch_variants_for_promotion_rules_no_applicable_variants(
- promotion_without_rules, category, channel_USD
+ catalogue_promotion_without_rules, category, channel_USD
):
# given
category.products.clear()
reward_value = Decimal("2")
- rule = promotion_without_rules.rules.create(
+ rule = catalogue_promotion_without_rules.rules.create(
name="Percentage promotion rule",
catalogue_predicate={
"categoryPredicate": {
@@ -101,7 +124,7 @@ def test_fetch_variants_for_promotion_rules_no_applicable_variants(
def test_fetch_variants_for_promotion_rules_relation_already_exist(
- promotion,
+ catalogue_promotion,
):
# given
PromotionRuleVariant = PromotionRule.variants.through
@@ -117,12 +140,12 @@ def test_fetch_variants_for_promotion_rules_relation_already_exist(
def test_fetch_variants_for_promotion_rules_discount_race_condition(
- promotion_without_rules,
+ catalogue_promotion_without_rules,
channel_USD,
product_variant_list,
):
# given
- promotion = promotion_without_rules
+ promotion = catalogue_promotion_without_rules
existing_variant = product_variant_list[0]
new_variant = product_variant_list[1]
diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.py
index d3ef61b06e..66f2f2ac37 100644
--- a/saleor/product/tests/test_product.py
+++ b/saleor/product/tests/test_product.py
@@ -302,7 +302,7 @@ def test_get_price_overridden_price_with_discount(
product_type,
category,
channel_USD,
- promotion_without_rules,
+ catalogue_promotion_without_rules,
):
# given
product = models.Product.objects.create(
@@ -324,7 +324,7 @@ def test_get_price_overridden_price_with_discount(
rule_1, rule_2 = PromotionRule.objects.bulk_create(
[
PromotionRule(
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
catalogue_predicate={
"productPredicate": {
"ids": [
@@ -336,7 +336,7 @@ def test_get_price_overridden_price_with_discount(
reward_value=reward_value_1,
),
PromotionRule(
- promotion=promotion_without_rules,
+ promotion=catalogue_promotion_without_rules,
catalogue_predicate={
"variantPredicate": {
"ids": [
diff --git a/saleor/product/tests/test_tasks.py b/saleor/product/tests/test_tasks.py
index 55bc6616ca..a1ea0c12fd 100644
--- a/saleor/product/tests/test_tasks.py
+++ b/saleor/product/tests/test_tasks.py
@@ -97,6 +97,34 @@ def test_update_products_discounted_prices_for_promotion_task(
) == set(PromotionRule.objects.values_list("id", flat=True))
+@patch(
+ "saleor.product.tasks.update_products_discounted_prices_for_promotion_task.delay"
+)
+@patch("saleor.product.tasks.PROMOTION_RULE_BATCH_SIZE", 1)
+@patch("saleor.product.tasks.update_discounted_prices_task.delay")
+def test_update_products_discounted_prices_for_promotion_task_with_order_predicate(
+ update_discounted_prices_task_mock,
+ update_products_discounted_prices_for_promotion_task_delay_mocked,
+ promotion_list,
+ product_list,
+):
+ # given
+ Promotion.objects.update(start_date=timezone.now() - timedelta(days=1))
+ product_ids = [product.id for product in product_list]
+ PromotionRule.objects.update(catalogue_predicate={})
+ PromotionRuleVariant = PromotionRule.variants.through
+
+ # when
+ update_products_discounted_prices_for_promotion_task(product_ids)
+
+ # then
+ assert not update_products_discounted_prices_for_promotion_task_delay_mocked.called
+ update_discounted_prices_task_mock.assert_called_once_with(product_ids)
+ assert set(
+ PromotionRuleVariant.objects.values_list("promotionrule_id", flat=True)
+ ) == set(PromotionRule.objects.values_list("id", flat=True))
+
+
@patch("saleor.product.tasks.PROMOTION_RULE_BATCH_SIZE", 1)
@patch("saleor.product.tasks.update_discounted_prices_task.delay")
@patch("saleor.product.utils.variants.fetch_variants_for_promotion_rules")
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index 60c0629b74..b82017a764 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -52,13 +52,15 @@ def get_variant_selection_attributes(
]
-def fetch_variants_for_promotion_rules(rules: QuerySet[PromotionRule]):
- from ...graphql.discount.utils import get_variants_for_predicate
+def fetch_variants_for_promotion_rules(
+ rules: QuerySet[PromotionRule],
+):
+ from ...graphql.discount.utils import get_variants_for_catalogue_predicate
PromotionRuleVariant = PromotionRule.variants.through
new_rules_variants = []
- for rule in list(rules.iterator()):
- variants = get_variants_for_predicate(rule.catalogue_predicate)
+ for rule in rules.iterator():
+ variants = get_variants_for_catalogue_predicate(rule.catalogue_predicate)
new_rules_variants.extend(
[
PromotionRuleVariant(
diff --git a/saleor/settings.py b/saleor/settings.py
index 043e87172b..5024f3f2d0 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -889,3 +889,6 @@ COMMON_REQUESTS_TIMEOUT = (REQUESTS_CONN_EST_TIMEOUT, 18)
WEBHOOK_TIMEOUT = (REQUESTS_CONN_EST_TIMEOUT, 18)
WEBHOOK_SYNC_TIMEOUT = (REQUESTS_CONN_EST_TIMEOUT, 18)
+
+# The max number of rules with order_predicate defined
+ORDER_RULES_LIMIT = os.environ.get("ORDER_RULES_LIMIT", 100)
diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.py
index c7c2d54d21..8d479c3295 100644
--- a/saleor/tax/tests/test_checkout_calculations.py
+++ b/saleor/tax/tests/test_checkout_calculations.py
@@ -7,6 +7,7 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.utils import add_variant_to_checkout
from ...core.prices import quantize_price
from ...core.taxes import zero_taxed_money
+from ...discount.utils import create_discount_objects_for_order_promotions
from ...plugins.manager import get_plugins_manager
from ...tax.models import TaxClassCountryRate
from .. import TaxCalculationStrategy
@@ -429,6 +430,48 @@ def test_calculate_checkout_subtotal_with_promotion_prices_not_entered_with_tax(
)
+def test_calculate_checkout_subtotal_with_order_promotion(
+ checkout_with_item_and_order_discount,
+ address,
+ shipping_zone,
+ stock,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ prices_entered_with_tax = True
+ _enable_flat_rates(checkout, prices_entered_with_tax)
+ discount_amount = checkout.discounts.first().amount_value
+
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.save()
+
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, [], manager)
+ lines, _ = fetch_checkout_lines(checkout)
+
+ # when
+ update_checkout_prices_with_flat_rates(
+ checkout,
+ checkout_info,
+ lines,
+ prices_entered_with_tax,
+ address,
+ )
+
+ # then
+ subtotal = Decimal("0.00")
+ for line_info in lines:
+ subtotal += (
+ line_info.channel_listing.discounted_price_amount * line_info.line.quantity
+ )
+ discounted_subtotal = subtotal - discount_amount
+ assert checkout.subtotal == TaxedMoney(
+ net=Money(round(discounted_subtotal / Decimal("1.23"), 2), "USD"),
+ gross=Money(discounted_subtotal, "USD"),
+ )
+
+
def test_calculate_checkout_line_total(checkout_with_item, shipping_zone, address):
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_item
@@ -768,6 +811,54 @@ def test_calculate_checkout_line_total_with_shipping_voucher(
)
+def test_calculate_checkout_line_total_discount_from_order_promotion(
+ checkout_with_item_and_order_discount, shipping_zone, address
+):
+ # given
+ manager = get_plugins_manager(allow_replica=False)
+ checkout = checkout_with_item_and_order_discount
+
+ rate = Decimal(23)
+ prices_entered_with_tax = True
+ _enable_flat_rates(checkout, prices_entered_with_tax)
+
+ line = checkout.lines.first()
+ assert line.quantity > 1
+
+ method = shipping_zone.shipping_methods.get()
+ checkout.shipping_address = address
+ checkout.shipping_method_name = method.name
+ checkout.shipping_method = method
+ checkout.save()
+
+ variant = line.variant
+ product = variant.product
+ product.tax_class.country_rates.update_or_create(country=address.country, rate=rate)
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ checkout_line_info = lines[0]
+ create_discount_objects_for_order_promotions(checkout_info, lines)
+
+ # when
+ line_price = calculate_checkout_line_total(
+ checkout_info, lines, checkout_line_info, rate, prices_entered_with_tax
+ )
+
+ # then
+ variant_listing = variant.channel_listings.get(channel=checkout.channel)
+ unit_price = variant.get_price(variant_listing)
+ total_price = unit_price * line.quantity
+ rule = checkout.discounts.first().promotion_rule
+ rule_reward = Money(rule.reward_value, checkout.currency)
+ assert line_price == TaxedMoney(
+ net=quantize_price(
+ (total_price - rule_reward) / Decimal("1.23"), checkout.currency
+ ),
+ gross=total_price - rule_reward,
+ )
+
+
def test_calculate_checkout_shipping(
checkout_with_item,
shipping_zone,
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py
index 5f5572c24f..7467ee834a 100644
--- a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_fixed_promotion.py
@@ -47,20 +47,26 @@ def test_checkout_products_on_fixed_promotion_core_2102(
discount_value = 5
discount_type = "FIXED"
promotion_rule_name = "rule for product"
+ promotion_type = "CATALOGUE"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ 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": discount_value,
+ "rewardValueType": "FIXED",
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py
index c506ae6459..710444bbc5 100644
--- a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_products_on_percentage_promotion.py
@@ -47,21 +47,25 @@ def test_checkout_products_on_percentage_promotion_core_2104(
discount_value = 3
discount_type = "PERCENTAGE"
promotion_rule_name = "rule for product"
+ promotion_type = "CATALOGUE"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
promotion_id = promotion_data["id"]
catalogue_predicate = {"productPredicate": {"ids": [product_id]}}
- promotion_rule = create_promotion_rule(
- e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
- )
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
+
+ promotion_rule = create_promotion_rule(e2e_staff_api_client, input)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
assert product_predicate[0] == product_id
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price_not.py b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price.py
similarity index 90%
rename from saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price_not.py
rename to saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price.py
index 6e09fe335f..d68265d00b 100644
--- a/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price_not.py
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_checkout_with_fixed_promotion_should_not_result_in_negative_price.py
@@ -38,10 +38,12 @@ def test_checkout_with_fixed_promotion_should_not_result_in_negative_price_CORE_
) = prepare_product(e2e_staff_api_client, warehouse_id, channel_id, variant_price=5)
promotion_name = "Promotion Fixed"
+ promotion_type = "CATALOGUE"
promotion_data = create_promotion(
e2e_staff_api_client,
promotion_name,
+ promotion_type,
)
promotion_id = promotion_data["id"]
@@ -54,14 +56,17 @@ def test_checkout_with_fixed_promotion_should_not_result_in_negative_price_CORE_
catalogue_predicate = {"productPredicate": {"ids": [product_id]}}
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_applied_on_checkout_with_specific_subtotal.py b/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_applied_on_checkout_with_specific_subtotal.py
new file mode 100644
index 0000000000..73c4216038
--- /dev/null
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_applied_on_checkout_with_specific_subtotal.py
@@ -0,0 +1,168 @@
+from decimal import Decimal
+
+import pytest
+
+from ......checkout.models import Checkout
+from ......discount import DiscountType, RewardValueType
+from ....product.utils.preparing_product import prepare_product
+from ....promotions.utils import create_promotion, create_promotion_rule
+from ....shop.utils.preparing_shop import prepare_default_shop
+from ....utils import assign_permissions
+from ...utils import (
+ checkout_complete,
+ checkout_create,
+ checkout_delivery_method_update,
+ checkout_dummy_payment_create,
+ checkout_lines_update,
+)
+
+
+def prepare_promotion(e2e_staff_api_client):
+ shop_data = prepare_default_shop(e2e_staff_api_client)
+ channel_id = shop_data["channel"]["id"]
+ channel_slug = shop_data["channel"]["slug"]
+ warehouse_id = shop_data["warehouse"]["id"]
+ shipping_method_id = shop_data["shipping_method"]["id"]
+
+ promotion_name = "Promotion"
+ promotion_type = "ORDER"
+
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
+ promotion_id = promotion_data["id"]
+ discount_value = 2.99
+ order_predicate_subtotal_value = "21"
+ order_predicate = {
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"eq": order_predicate_subtotal_value}
+ }
+ }
+
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": "test rule",
+ "orderPredicate": order_predicate,
+ "rewardType": "SUBTOTAL_DISCOUNT",
+ "rewardValue": discount_value,
+ "rewardValueType": "FIXED",
+ }
+
+ promotion_rule = create_promotion_rule(e2e_staff_api_client, input)
+ assert promotion_rule["orderPredicate"] == order_predicate
+ assert promotion_rule["channels"][0]["id"] == channel_id
+
+ return (
+ channel_id,
+ channel_slug,
+ shipping_method_id,
+ warehouse_id,
+ promotion_id,
+ discount_value,
+ order_predicate_subtotal_value,
+ )
+
+
+def test_promotion_applied_on_checkout_with_specific_subtotal_CORE_2133(
+ e2e_staff_api_client,
+ e2e_not_logged_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)
+
+ (
+ channel_id,
+ channel_slug,
+ shipping_method_id,
+ warehouse_id,
+ promotion_id,
+ discount_value,
+ order_predicate_subtotal_value,
+ ) = prepare_promotion(e2e_staff_api_client)
+ (
+ _product_id,
+ product_variant_id,
+ product_variant_price,
+ ) = prepare_product(e2e_staff_api_client, warehouse_id, channel_id, variant_price=7)
+
+ # Step 1 - Create checkout with 5 product variants
+ lines = [{"variantId": product_variant_id, "quantity": 5}]
+ data = checkout_create(
+ e2e_not_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = data["id"]
+ checkout_db = Checkout.objects.first()
+ total = data["totalPrice"]["gross"]["amount"]
+ subtotal = data["subtotalPrice"]["gross"]["amount"]
+ assert data["billingAddress"] is not None
+ assert data["shippingAddress"] is not None
+ assert checkout_id is not None
+ assert data["lines"][0]["variant"]["id"] == product_variant_id
+ assert data["discount"]["amount"] == 0.00
+ assert subtotal != order_predicate_subtotal_value
+ assert not checkout_db.discounts.all()
+
+ # Step 2 - Add shipping method
+ checkout_data = checkout_delivery_method_update(
+ e2e_not_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ shipping_price = checkout_data["shippingPrice"]["gross"]["amount"]
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+
+ # Step 3 - Update checkout lines to only 3 product variants
+ lines = [{"variantId": product_variant_id, "quantity": 3}]
+ checkout_lines = checkout_lines_update(
+ e2e_not_logged_api_client, checkout_id, lines
+ )
+ discounted_subtotal = checkout_lines["checkout"]["subtotalPrice"]["gross"]["amount"]
+ total_gross = checkout_lines["checkout"]["totalPrice"]["gross"]["amount"]
+ undiscounted_subtotal = checkout_lines["checkout"]["lines"][0][
+ "undiscountedTotalPrice"
+ ]["amount"]
+ unit_price = checkout_lines["checkout"]["lines"][0]["unitPrice"]["gross"]["amount"]
+ assert unit_price == round((float(undiscounted_subtotal) - discount_value) / 3, 2)
+ undiscounted_unit_price = checkout_lines["checkout"]["lines"][0][
+ "undiscountedUnitPrice"
+ ]["amount"]
+ assert undiscounted_unit_price == float(product_variant_price)
+ assert discounted_subtotal == round(
+ float(undiscounted_subtotal - discount_value), 2
+ )
+ discounted_total = discounted_subtotal + shipping_price
+ assert checkout_lines["checkout"]["discount"]["amount"] == discount_value
+ assert total_gross != total
+ assert total_gross == discounted_total
+ assert undiscounted_subtotal == float(order_predicate_subtotal_value)
+ discounts_db = checkout_db.discounts.all()
+ assert len(discounts_db) == 1
+ discount_db = discounts_db[0]
+ assert discount_db.type == DiscountType.ORDER_PROMOTION.lower()
+ assert discount_db.value == Decimal(str(discount_value))
+ assert discount_db.value_type == RewardValueType.FIXED.lower()
+ assert discount_db.amount_value == Decimal(str(discount_value))
+
+ # Step 4 - Create payment
+ checkout_dummy_payment_create(e2e_not_logged_api_client, checkout_id, total_gross)
+
+ # Step 5 - Complete the checkout
+ order_data = checkout_complete(e2e_not_logged_api_client, checkout_id)
+ assert order_data["status"] == "UNFULFILLED"
+ assert order_data["total"]["gross"]["amount"] == discounted_total
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_applied_on_checkout_with_subtotal_within_specified_range.py b/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_applied_on_checkout_with_subtotal_within_specified_range.py
new file mode 100644
index 0000000000..6ead0850d2
--- /dev/null
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_applied_on_checkout_with_subtotal_within_specified_range.py
@@ -0,0 +1,305 @@
+from decimal import Decimal
+
+import pytest
+
+from ......checkout.models import Checkout
+from ......discount import DiscountType, RewardValueType
+from ....product.utils.preparing_product import prepare_product
+from ....promotions.utils import (
+ create_promotion,
+ create_promotion_rule,
+)
+from ....shop.utils.preparing_shop import prepare_default_shop
+from ....utils import assign_permissions
+from ...utils import (
+ checkout_complete,
+ checkout_create,
+ checkout_delivery_method_update,
+ checkout_dummy_payment_create,
+ checkout_lines_update,
+)
+
+
+def prepare_promotion(e2e_staff_api_client):
+ shop_data = prepare_default_shop(e2e_staff_api_client)
+ channel_id = shop_data["channel"]["id"]
+ channel_slug = shop_data["channel"]["slug"]
+ warehouse_id = shop_data["warehouse"]["id"]
+ shipping_method_id = shop_data["shipping_method"]["id"]
+
+ promotion_name = "Promotion"
+
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type="ORDER"
+ )
+ promotion_id = promotion_data["id"]
+
+ return (
+ channel_id,
+ channel_slug,
+ shipping_method_id,
+ warehouse_id,
+ promotion_id,
+ )
+
+
+def test_promotion_applied_on_checkout_with_subtotal_with_specified_gte_range_CORE_2136(
+ e2e_staff_api_client,
+ e2e_not_logged_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)
+
+ (
+ channel_id,
+ channel_slug,
+ shipping_method_id,
+ warehouse_id,
+ promotion_id,
+ ) = prepare_promotion(e2e_staff_api_client)
+ discount_value = 20
+
+ order_predicate_subtotal_gte_value = "10"
+ order_predicate = {
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"range": {"gte": order_predicate_subtotal_gte_value}}
+ }
+ }
+
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": "test rule",
+ "orderPredicate": order_predicate,
+ "rewardType": "SUBTOTAL_DISCOUNT",
+ "rewardValue": discount_value,
+ "rewardValueType": "PERCENTAGE",
+ }
+
+ promotion_rule = create_promotion_rule(e2e_staff_api_client, input)
+ assert promotion_rule["orderPredicate"] == order_predicate
+ assert promotion_rule["channels"][0]["id"] == channel_id
+ (
+ _product_id,
+ product_variant_id,
+ product_variant_price,
+ ) = prepare_product(
+ e2e_staff_api_client, warehouse_id, channel_id, variant_price=2.99
+ )
+
+ order_predicate_subtotal_gte_value = float(order_predicate_subtotal_gte_value)
+
+ # Step 1 - Create checkout with subtotal lesser than gte value
+ lines = [{"variantId": product_variant_id, "quantity": 3}]
+ data = checkout_create(
+ e2e_not_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = data["id"]
+ checkout_db = Checkout.objects.first()
+ total = data["totalPrice"]["gross"]["amount"]
+ subtotal = data["subtotalPrice"]["gross"]["amount"]
+ assert data["billingAddress"] is not None
+ assert data["shippingAddress"] is not None
+ assert checkout_id is not None
+ assert data["lines"][0]["variant"]["id"] == product_variant_id
+ assert data["discount"]["amount"] == 0.00
+ assert subtotal <= order_predicate_subtotal_gte_value
+ assert not checkout_db.discounts.all()
+
+ # Step 2 - Update checkout lines so subtotal is within the specified gte range
+ lines = [{"variantId": product_variant_id, "quantity": 4}]
+ checkout_lines = checkout_lines_update(
+ e2e_not_logged_api_client, checkout_id, lines
+ )
+ discounted_subtotal = checkout_lines["checkout"]["subtotalPrice"]["gross"]["amount"]
+ total_gross = checkout_lines["checkout"]["totalPrice"]["gross"]["amount"]
+ undiscounted_subtotal = checkout_lines["checkout"]["lines"][0][
+ "undiscountedTotalPrice"
+ ]["amount"]
+ undiscounted_subtotal = float(undiscounted_subtotal)
+ unit_price = checkout_lines["checkout"]["lines"][0]["unitPrice"]["gross"]["amount"]
+ discount = round((undiscounted_subtotal) * discount_value / 100, 2)
+
+ assert unit_price == round((undiscounted_subtotal - discount) / 4, 2)
+ undiscounted_unit_price = checkout_lines["checkout"]["lines"][0][
+ "undiscountedUnitPrice"
+ ]["amount"]
+ assert undiscounted_unit_price == float(product_variant_price)
+
+ assert discounted_subtotal == undiscounted_subtotal - discount
+ assert checkout_lines["checkout"]["discount"]["amount"] == discount
+ assert total_gross != total
+ assert order_predicate_subtotal_gte_value <= undiscounted_subtotal
+ discounts_db = checkout_db.discounts.all()
+ assert len(discounts_db) == 1
+ discount_db = discounts_db[0]
+ assert discount_db.type == DiscountType.ORDER_PROMOTION.lower()
+ assert discount_db.value == discount_value
+ assert discount_db.value_type == RewardValueType.PERCENTAGE.lower()
+ assert discount_db.amount_value == Decimal(str(discount))
+
+ # Step 3 - Add shipping method
+ checkout_data = checkout_delivery_method_update(
+ e2e_not_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ shipping_price = checkout_data["shippingPrice"]["gross"]["amount"]
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+ discounted_total = discounted_subtotal + shipping_price
+
+ # Step 4 - Create payment
+ checkout_dummy_payment_create(
+ e2e_not_logged_api_client, checkout_id, discounted_total
+ )
+
+ # Step 5 - Complete the checkout
+ order_data = checkout_complete(e2e_not_logged_api_client, checkout_id)
+ assert order_data["status"] == "UNFULFILLED"
+ assert order_data["total"]["gross"]["amount"] == discounted_total
+
+
+def test_promotion_applied_on_checkout_with_subtotal_with_specified_lte_range_CORE_2136(
+ e2e_staff_api_client,
+ e2e_not_logged_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)
+
+ (
+ channel_id,
+ channel_slug,
+ shipping_method_id,
+ warehouse_id,
+ promotion_id,
+ ) = prepare_promotion(e2e_staff_api_client)
+ discount_value = 2
+
+ order_predicate_subtotal_lte_value = "6"
+ order_predicate = {
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"range": {"lte": order_predicate_subtotal_lte_value}}
+ }
+ }
+
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": "test rule",
+ "orderPredicate": order_predicate,
+ "rewardType": "SUBTOTAL_DISCOUNT",
+ "rewardValue": discount_value,
+ "rewardValueType": "FIXED",
+ }
+
+ promotion_rule = create_promotion_rule(e2e_staff_api_client, input)
+ assert promotion_rule["orderPredicate"] == order_predicate
+ assert promotion_rule["channels"][0]["id"] == channel_id
+ (
+ _product_id,
+ product_variant_id,
+ product_variant_price,
+ ) = prepare_product(
+ e2e_staff_api_client, warehouse_id, channel_id, variant_price=2.99
+ )
+
+ order_predicate_subtotal_gte_value = float(order_predicate_subtotal_lte_value)
+
+ # Step 1 - Create checkout with subtotal greater than lte value
+ lines = [{"variantId": product_variant_id, "quantity": 3}]
+ data = checkout_create(
+ e2e_not_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = data["id"]
+ checkout_db = Checkout.objects.first()
+ total = data["totalPrice"]["gross"]["amount"]
+ subtotal = data["subtotalPrice"]["gross"]["amount"]
+ assert data["billingAddress"] is not None
+ assert data["shippingAddress"] is not None
+ assert checkout_id is not None
+ assert data["lines"][0]["variant"]["id"] == product_variant_id
+ assert data["discount"]["amount"] == 0.00
+ assert subtotal >= order_predicate_subtotal_gte_value
+ assert not checkout_db.discounts.all()
+
+ # Step 2 - Update checkout lines so subtotal is within the specified lte range
+ lines = [{"variantId": product_variant_id, "quantity": 1}]
+ checkout_lines = checkout_lines_update(
+ e2e_not_logged_api_client, checkout_id, lines
+ )
+ total_gross = checkout_lines["checkout"]["totalPrice"]["gross"]["amount"]
+ undiscounted_subtotal = checkout_lines["checkout"]["lines"][0][
+ "undiscountedTotalPrice"
+ ]["amount"]
+ undiscounted_subtotal = float(undiscounted_subtotal)
+ discounted_subtotal = checkout_lines["checkout"]["lines"][0]["totalPrice"]["gross"][
+ "amount"
+ ]
+ unit_price = checkout_lines["checkout"]["lines"][0]["unitPrice"]["gross"]["amount"]
+ assert unit_price == discounted_subtotal
+ undiscounted_unit_price = checkout_lines["checkout"]["lines"][0][
+ "undiscountedUnitPrice"
+ ]["amount"]
+ assert undiscounted_unit_price == float(product_variant_price)
+
+ assert discounted_subtotal == round((undiscounted_subtotal - discount_value), 2)
+ assert checkout_lines["checkout"]["discount"]["amount"] == discount_value
+ assert total_gross != total
+ assert order_predicate_subtotal_gte_value >= undiscounted_subtotal
+ discounts_db = checkout_db.discounts.all()
+ assert len(discounts_db) == 1
+ discount_db = discounts_db[0]
+ assert discount_db.type == DiscountType.ORDER_PROMOTION.lower()
+ assert discount_db.value == discount_value
+ assert discount_db.value_type == RewardValueType.FIXED.lower()
+ assert discount_db.amount_value == discount_value
+
+ # Step 3 - Add shipping method
+ checkout_data = checkout_delivery_method_update(
+ e2e_not_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ shipping_price = checkout_data["shippingPrice"]["gross"]["amount"]
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+ discounted_total = discounted_subtotal + shipping_price
+
+ # Step 4 - Create payment
+ checkout_dummy_payment_create(
+ e2e_not_logged_api_client, checkout_id, discounted_total
+ )
+
+ # Step 5 - Complete the checkout
+ order_data = checkout_complete(e2e_not_logged_api_client, checkout_id)
+ assert order_data["status"] == "UNFULFILLED"
+ assert order_data["total"]["gross"]["amount"] == discounted_total
diff --git a/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_discount_applied_on_checkout_with_specific_total_and_subtotal.py b/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_discount_applied_on_checkout_with_specific_total_and_subtotal.py
new file mode 100644
index 0000000000..50d8f0bd8d
--- /dev/null
+++ b/saleor/tests/e2e/checkout/discounts/promotions/test_promotion_discount_applied_on_checkout_with_specific_total_and_subtotal.py
@@ -0,0 +1,182 @@
+from decimal import Decimal
+
+import pytest
+
+from ......checkout.models import Checkout
+from ......discount import DiscountType, RewardValueType
+from ....product.utils.preparing_product import prepare_product
+from ....promotions.utils import create_promotion, create_promotion_rule
+from ....shop.utils.preparing_shop import prepare_default_shop
+from ....utils import assign_permissions
+from ...utils import (
+ checkout_complete,
+ checkout_create,
+ checkout_delivery_method_update,
+ checkout_dummy_payment_create,
+ checkout_lines_update,
+)
+
+
+def prepare_promotion(e2e_staff_api_client):
+ shop_data = prepare_default_shop(e2e_staff_api_client)
+ channel_id = shop_data["channel"]["id"]
+ channel_slug = shop_data["channel"]["slug"]
+ warehouse_id = shop_data["warehouse"]["id"]
+ shipping_method_id = shop_data["shipping_method"]["id"]
+
+ promotion_name = "Promotion"
+ promotion_type = "ORDER"
+
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
+
+ promotion_id = promotion_data["id"]
+ discount_value = 25
+ order_predicate_subtotal_value = "79.96"
+ order_predicate_total_value = "89.96"
+ order_predicate = {
+ "AND": [
+ {
+ "discountedObjectPredicate": {
+ "baseSubtotalPrice": {"eq": order_predicate_subtotal_value}
+ }
+ },
+ {
+ "discountedObjectPredicate": {
+ "baseTotalPrice": {"eq": order_predicate_total_value},
+ }
+ },
+ ]
+ }
+
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": "test rule",
+ "orderPredicate": order_predicate,
+ "rewardType": "SUBTOTAL_DISCOUNT",
+ "rewardValue": discount_value,
+ "rewardValueType": "PERCENTAGE",
+ }
+
+ promotion_rule = create_promotion_rule(e2e_staff_api_client, input)
+ promotion_rule_id = promotion_rule["id"]
+ assert promotion_rule["orderPredicate"] == order_predicate
+ assert promotion_rule["channels"][0]["id"] == channel_id
+
+ return (
+ channel_id,
+ channel_slug,
+ shipping_method_id,
+ warehouse_id,
+ promotion_id,
+ promotion_rule_id,
+ discount_value,
+ order_predicate_total_value,
+ order_predicate_subtotal_value,
+ )
+
+
+def test_promotion_discount_applied_on_checkout_with_specific_total_and_subtotal_CORE_2134(
+ e2e_staff_api_client,
+ e2e_not_logged_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)
+
+ (
+ channel_id,
+ channel_slug,
+ shipping_method_id,
+ warehouse_id,
+ promotion_id,
+ promotion_rule_id,
+ discount_value,
+ order_predicate_total_value,
+ order_predicate_subtotal_value,
+ ) = prepare_promotion(e2e_staff_api_client)
+ (
+ _product_id,
+ product_variant_id,
+ product_variant_price,
+ ) = prepare_product(
+ e2e_staff_api_client, warehouse_id, channel_id, variant_price=19.99
+ )
+
+ # Step 1 - Create checkout with 1 product variant
+ lines = [{"variantId": product_variant_id, "quantity": 1}]
+ data = checkout_create(
+ e2e_not_logged_api_client,
+ lines,
+ channel_slug,
+ set_default_billing_address=True,
+ set_default_shipping_address=True,
+ )
+ checkout_id = data["id"]
+ checkout_db = Checkout.objects.first()
+ total = data["totalPrice"]["gross"]["amount"]
+ subtotal = data["subtotalPrice"]["gross"]["amount"]
+ assert data["billingAddress"] is not None
+ assert data["shippingAddress"] is not None
+ assert checkout_id is not None
+ assert data["lines"][0]["variant"]["id"] == product_variant_id
+ assert data["discount"]["amount"] == 0.00
+ assert total != order_predicate_total_value
+ assert subtotal != order_predicate_subtotal_value
+ assert not checkout_db.discounts.all()
+
+ # Step 2 - Add shipping method
+ checkout_data = checkout_delivery_method_update(
+ e2e_not_logged_api_client,
+ checkout_id,
+ shipping_method_id,
+ )
+ shipping_price = checkout_data["shippingPrice"]["gross"]["amount"]
+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id
+
+ # Step 3 - Update checkout lines to 4 product variants
+ lines = [{"variantId": product_variant_id, "quantity": 4}]
+ checkout_lines = checkout_lines_update(
+ e2e_not_logged_api_client, checkout_id, lines
+ )
+ discounted_subtotal = checkout_lines["checkout"]["subtotalPrice"]["gross"]["amount"]
+ total_gross = checkout_lines["checkout"]["totalPrice"]["gross"]["amount"]
+ undiscounted_subtotal = checkout_lines["checkout"]["lines"][0][
+ "undiscountedTotalPrice"
+ ]["amount"]
+ undiscounted_total = undiscounted_subtotal + shipping_price
+ discount = round(float(undiscounted_subtotal) * discount_value / 100, 2)
+ discounted_total = discounted_subtotal + shipping_price
+ assert discounted_subtotal == undiscounted_subtotal - discount
+ assert checkout_lines["checkout"]["discount"]["amount"] == discount
+ assert total_gross != total
+ assert total_gross == discounted_total
+ assert undiscounted_total == float(order_predicate_total_value)
+ assert undiscounted_subtotal == float(order_predicate_subtotal_value)
+ discounts_db = checkout_db.discounts.all()
+ assert len(discounts_db) == 1
+ discount_db = discounts_db[0]
+ assert discount_db.type == DiscountType.ORDER_PROMOTION.lower()
+ assert discount_db.value == Decimal(discount_value)
+ assert discount_db.value_type == RewardValueType.PERCENTAGE.lower()
+ assert discount_db.amount_value == Decimal(str(discount))
+
+ # Step 4 - Create payment
+ checkout_dummy_payment_create(e2e_not_logged_api_client, checkout_id, total_gross)
+
+ # Step 5 - Complete the checkout
+ order_data = checkout_complete(e2e_not_logged_api_client, checkout_id)
+ assert order_data["status"] == "UNFULFILLED"
+ assert order_data["total"]["gross"]["amount"] == discounted_total
diff --git a/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py b/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py
index cc5fd01bcc..3652876b2d 100644
--- a/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py
+++ b/saleor/tests/e2e/checkout/discounts/test_checkout_with_promotion_and_voucher.py
@@ -23,14 +23,16 @@ def prepare_promotion(
e2e_staff_api_client,
product_id,
channel_id,
- promotion_type,
promotion_value,
+ promotion_value_type,
):
promotion_name = "test_promotion"
+ promotion_type = "CATALOGUE"
promotion_data = create_promotion(
e2e_staff_api_client,
promotion_name,
+ promotion_type,
)
promotion_id = promotion_data["id"]
@@ -41,15 +43,17 @@ def prepare_promotion(
catalogue_predicate = {
"productPredicate": {"ids": [product_id]},
}
-
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": promotion_value,
+ "rewardValueType": promotion_value_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- promotion_type,
- promotion_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
@@ -104,7 +108,7 @@ def prepare_voucher(
(
"variant_price",
"promotion_value",
- "promotion_type",
+ "promotion_value_type",
"expected_promotion_discount",
"voucher_discount_value",
"voucher_discount_type",
@@ -125,7 +129,7 @@ def test_checkout_with_promotion_and_voucher_CORE_2107(
permission_manage_product_types_and_attributes,
permission_manage_discounts,
variant_price,
- promotion_type,
+ promotion_value_type,
promotion_value,
expected_promotion_discount,
voucher_discount_value,
@@ -162,8 +166,8 @@ def test_checkout_with_promotion_and_voucher_CORE_2107(
e2e_staff_api_client,
product_id,
channel_id,
- promotion_type,
promotion_value,
+ promotion_value_type,
)
voucher_discount_value, voucher_code = prepare_voucher(
diff --git a/saleor/tests/e2e/checkout/utils/checkout_complete.py b/saleor/tests/e2e/checkout/utils/checkout_complete.py
index f338f0f9eb..b1d0c4b341 100644
--- a/saleor/tests/e2e/checkout/utils/checkout_complete.py
+++ b/saleor/tests/e2e/checkout/utils/checkout_complete.py
@@ -78,6 +78,8 @@ mutation CheckoutComplete($checkoutId: ID!) {
}
}
discounts {
+ id
+ name
type
value
}
diff --git a/saleor/tests/e2e/checkout/utils/checkout_create.py b/saleor/tests/e2e/checkout/utils/checkout_create.py
index d92e309ef3..d45440bb05 100644
--- a/saleor/tests/e2e/checkout/utils/checkout_create.py
+++ b/saleor/tests/e2e/checkout/utils/checkout_create.py
@@ -19,6 +19,15 @@ mutation CreateCheckout($input: CheckoutCreateInput!) {
channel {
slug
}
+ discountName
+ discount {
+ amount
+ }
+ shippingPrice {
+ gross {
+ amount
+ }
+ }
totalPrice {
gross {
amount
@@ -30,6 +39,11 @@ mutation CreateCheckout($input: CheckoutCreateInput!) {
amount
}
}
+ subtotalPrice {
+ gross {
+ amount
+ }
+ }
created
isShippingRequired
billingAddress {
diff --git a/saleor/tests/e2e/checkout/utils/checkout_lines_update.py b/saleor/tests/e2e/checkout/utils/checkout_lines_update.py
index beecf992d8..3fd8514e0c 100644
--- a/saleor/tests/e2e/checkout/utils/checkout_lines_update.py
+++ b/saleor/tests/e2e/checkout/utils/checkout_lines_update.py
@@ -1,15 +1,45 @@
from ...utils import get_graphql_content
CHECKOUT_LINES_UPDATE_MUTATION = """
-mutation checkoutLinesUpdate($checkoutId: ID!, $lines: [CheckoutLineUpdateInput!]! ){
+mutation checkoutLinesUpdate($checkoutId: ID!, $lines: [CheckoutLineUpdateInput!]!) {
checkoutLinesUpdate(lines: $lines, checkoutId: $checkoutId) {
checkout {
+ discountName
+ discount {
+ amount
+ }
+ subtotalPrice {
+ gross {
+ amount
+ }
+ }
+ totalPrice {
+ gross {
+ amount
+ }
+ }
lines {
quantity
+ undiscountedTotalPrice {
+ amount
+ }
variant {
id
quantityLimitPerCustomer
}
+ unitPrice {
+ gross {
+ amount
+ }
+ }
+ undiscountedUnitPrice {
+ amount
+ }
+ totalPrice {
+ gross {
+ amount
+ }
+ }
}
}
errors {
diff --git a/saleor/tests/e2e/checkout/utils/query_checkout.py b/saleor/tests/e2e/checkout/utils/query_checkout.py
index 60810bbd7b..4078d15bd6 100644
--- a/saleor/tests/e2e/checkout/utils/query_checkout.py
+++ b/saleor/tests/e2e/checkout/utils/query_checkout.py
@@ -19,6 +19,17 @@ query Checkout($checkoutId: ID!){
amount
}
}
+ subtotalPrice {
+ gross {
+ amount
+ }
+ net {
+ amount
+ }
+ tax {
+ amount
+ }
+ }
availablePaymentGateways{
id
name
diff --git a/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py b/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py
index eea8f5133f..3dd41986a9 100644
--- a/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py
+++ b/saleor/tests/e2e/orders/discounts/test_apply_better_promotion_to_product.py
@@ -18,18 +18,22 @@ def prepare_promotion_with_rules(
channel_id,
product_id,
):
- promotion = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_type = "CATALOGUE"
+ promotion = create_promotion(e2e_staff_api_client, promotion_name, promotion_type)
promotion_id = promotion["id"]
catalogue_predicate = {"productPredicate": {"ids": [product_id]}}
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py b/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
index adf879ad57..702d3930d2 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
@@ -46,20 +46,25 @@ def test_order_products_on_percentage_promotion_CORE_2103(
discount_value = 10
discount_type = "PERCENTAGE"
promotion_rule_name = "rule for product"
+ promotion_type = "CATALOGUE"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ 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": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py b/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py
index ff33bd3413..33b5e8692e 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_from_the_same_category_on_fixed_promotion.py
@@ -94,21 +94,26 @@ def prepare_product(
variant_price_2,
)
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_type = "CATALOGUE"
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
promotion_id = promotion_data["id"]
catalogue_predicate = {
"categoryPredicate": {"ids": category_ids},
}
-
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
category_predicate = promotion_rule["cataloguePredicate"]["categoryPredicate"][
"ids"
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py
index 922ac04ae4..91c39e7521 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_fixed_promotion.py
@@ -48,19 +48,25 @@ def test_order_products_on_fixed_promotion_CORE_2101(
e2e_staff_api_client, warehouse_id, channel_id, variant_price=20
)
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ 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": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
index 547a5f6f7e..11bf9b6634 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
@@ -54,19 +54,24 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
discount_type = "PERCENTAGE"
promotion_rule_name = "rule for product"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ 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": promotion_discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- promotion_discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py b/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
index 5d10f97138..7971a9d197 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_promotion_not_applied_when_not_within_time_range.py
@@ -54,9 +54,11 @@ def test_order_promotion_not_applied_when_not_within_time_range_CORE_2110(
)
# Step 1 - Create promotion lasting for a specific time range
+ promotion_type = "CATALOGUE"
promotion_data = create_promotion(
e2e_staff_api_client,
promotion_name,
+ promotion_type,
start_date=tomorrow,
end_date=month_after,
)
@@ -70,14 +72,17 @@ def test_order_promotion_not_applied_when_not_within_time_range_CORE_2110(
catalogue_predicate = {"productPredicate": {"ids": [product_id]}}
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py b/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py
index ddd97505fd..aaec1a842b 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_promotion_still_applied_to_the_order_when_promotion_is_removed.py
@@ -55,19 +55,24 @@ def test_order_promotion_still_applied_to_the_order_when_promotion_is_removed_CO
e2e_staff_api_client, warehouse_id, channel_id, variant_price=20
)
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ 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": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py b/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py
index b3f25be241..6a7beaf49a 100644
--- a/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py
+++ b/saleor/tests/e2e/product/test_product_no_longer_on_promotion_when_promotion_is_removed.py
@@ -45,19 +45,25 @@ def test_product_no_longer_on_promotion_when_promotion_is_removed_CORE_2114(
discount_value = 5
discount_type = "FIXED"
promotion_rule_name = "rule for product"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ 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": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- catalogue_predicate,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
product_predicate = promotion_rule["cataloguePredicate"]["productPredicate"]["ids"]
assert promotion_rule["channels"][0]["id"] == channel_id
diff --git a/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py b/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py
index dd369a1bbc..ea82381409 100644
--- a/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py
+++ b/saleor/tests/e2e/promotions/test_promotions_query_with_different_parameters.py
@@ -22,9 +22,10 @@ def test_step_1_query_promotions_first_10_CORE_2118(
[permission_manage_discounts],
)
+ promotion_type = "CATALOGUE"
for i in range(11):
promotion_name = f"Promotion first {i + 1}"
- create_promotion(e2e_staff_api_client, promotion_name)
+ create_promotion(e2e_staff_api_client, promotion_name, promotion_type)
promotions_list = promotions_query(e2e_staff_api_client, first=10)
@@ -42,11 +43,14 @@ def test_step_2_query_promotions_first_10_created_at_CORE_2118(
[permission_manage_discounts],
)
- promotion_dnm = create_promotion(e2e_staff_api_client, "Promotion does not match")
+ promotion_type = "CATALOGUE"
+ promotion_dnm = create_promotion(
+ e2e_staff_api_client, "Promotion does not match", promotion_type
+ )
for i in range(10):
promotion_name = f"Promotion {i + 1}"
- create_promotion(e2e_staff_api_client, promotion_name)
+ create_promotion(e2e_staff_api_client, promotion_name, promotion_type)
promotions_list = promotions_query(
e2e_staff_api_client,
@@ -79,7 +83,10 @@ def test_step_3_query_promotions_first_10_start_date_before_CORE_2118(
[permission_manage_discounts],
)
- promotion_dnm = create_promotion(e2e_staff_api_client, "Promotion does not match")
+ promotion_type = "CATALOGUE"
+ promotion_dnm = create_promotion(
+ e2e_staff_api_client, "Promotion does not match", promotion_type
+ )
base_date = datetime(2023, 1, 1, 14, 1, 34, 61119)
@@ -88,7 +95,10 @@ def test_step_3_query_promotions_first_10_start_date_before_CORE_2118(
promotion_name = f"Promotion start date before {i + 1}"
start_date = (base_date - timedelta(days=i + 1)).isoformat() + "+00:00"
promotion = create_promotion(
- e2e_staff_api_client, promotion_name, start_date
+ e2e_staff_api_client,
+ promotion_name,
+ promotion_type,
+ start_date=start_date,
)
assert promotion["startDate"] == start_date
@@ -135,7 +145,9 @@ def test_step_4_old_sales_CORE_2118(
sale_type="FIXED",
)
- promotion_dnm = create_promotion(e2e_staff_api_client, "Promotion does not match")
+ promotion_dnm = create_promotion(
+ e2e_staff_api_client, "Promotion does not match", "CATALOGUE"
+ )
old_sale_promotions = promotions_query(
e2e_staff_api_client,
@@ -160,10 +172,13 @@ def test_step_5_promotions_with_metadata_CORE_211(
)
metadata = []
+ promotion_type = "CATALOGUE"
for i in range(10):
promotion_name = f"Promotion with metadata {i + 1}"
- promotion_with_metadata = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_with_metadata = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
promotion_id = promotion_with_metadata["id"]
assert promotion_id is not None
@@ -173,7 +188,10 @@ def test_step_5_promotions_with_metadata_CORE_211(
promotion_id,
metadata,
)
- promotion_dnm = create_promotion(e2e_staff_api_client, "Promotion does not match")
+
+ promotion_dnm = create_promotion(
+ e2e_staff_api_client, "Promotion does not match", promotion_type
+ )
promotions_list = promotions_query(
e2e_staff_api_client, first=11, where={"metadata": [{"key": "pub"}]}
@@ -196,17 +214,16 @@ def test_step_6_promotions_with_one_of_names_CORE_2118(
[permission_manage_discounts],
)
+ promotion_type = "CATALOGUE"
for i in range(3):
promotion_name = f"Promotion {i + 1}"
- create_promotion(
- e2e_staff_api_client,
- promotion_name,
- )
+ create_promotion(e2e_staff_api_client, promotion_name, promotion_type)
for i in range(3):
promotion_name = f"Test {i + 1}"
create_promotion(
e2e_staff_api_client,
promotion_name,
+ promotion_type,
)
promotions_list = promotions_query(
e2e_staff_api_client,
@@ -228,11 +245,13 @@ def test_step_7_promotions_with_name_eq_CORE_2118(
e2e_staff_api_client,
[permission_manage_discounts],
)
+ promotion_type = "CATALOGUE"
for i in range(3):
promotion_name = f"Promotion {i + 1}"
create_promotion(
e2e_staff_api_client,
promotion_name,
+ promotion_type,
)
promotions_list = promotions_query(
e2e_staff_api_client,
@@ -262,7 +281,7 @@ def test_step_8_query_old_sales_with_name_CORE_2118(
sale_type="FIXED",
)
- promotion_dnm = create_promotion(e2e_staff_api_client, "Old sale 2")
+ promotion_dnm = create_promotion(e2e_staff_api_client, "Old sale 2", "CATALOGUE")
promotions = promotions_query(
e2e_staff_api_client,
@@ -326,6 +345,7 @@ def test_step_10_promotions_with_end_date_after_CORE_2118(
)
base_date = datetime(2023, 1, 1, 14, 1, 34, 61119)
now = base_date.isoformat()
+ promotion_type = "CATALOGUE"
with freeze_time(now):
for i in range(10):
@@ -337,6 +357,7 @@ def test_step_10_promotions_with_end_date_after_CORE_2118(
promotion = create_promotion(
e2e_staff_api_client,
promotion_name,
+ promotion_type,
start_date="2023-10-04T00:00:00+02:00",
end_date=end_date,
)
@@ -345,6 +366,7 @@ def test_step_10_promotions_with_end_date_after_CORE_2118(
promotion_dnm = create_promotion(
e2e_staff_api_client,
"Promotion does not match",
+ promotion_type,
end_date="2024-12-31T21:00:00.000000+00:00",
)
@@ -386,9 +408,12 @@ def test_step_11_promotions_with_no_date_CORE_2118(
e2e_staff_api_client,
[permission_manage_discounts],
)
+ promotion_type = "CATALOGUE"
for i in range(10):
promotion_name = f"Promotion without end date {i + 1}"
- promotion = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
assert promotion["endDate"] is None
base_date = datetime(2023, 1, 1, 14, 1, 34, 61119)
@@ -401,6 +426,7 @@ def test_step_11_promotions_with_no_date_CORE_2118(
promotion_dnm = create_promotion(
e2e_staff_api_client,
promotion_name="With end date",
+ promotion_type=promotion_type,
start_date="2023-10-04T00:00:00+02:00",
end_date=end_date,
)
diff --git a/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py b/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py
index 14287a1db3..75e720586c 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py
@@ -27,21 +27,27 @@ def prepare_promotion(
channel_id=None,
):
promotion_name = "Promotion Test"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_type = "CATALOGUE"
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
promotion_id = promotion_data["id"]
predicate_input = {"collectionPredicate": {"ids": collection_ids}}
- promotion_rule_data = create_promotion_rule(
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": predicate_input,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
+ promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- predicate_input,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
- promotion_rule_id = promotion_rule_data["id"]
- discount_value = promotion_rule_data["rewardValue"]
+ promotion_rule_id = promotion_rule["id"]
+ discount_value = promotion_rule["rewardValue"]
return promotion_rule_id, discount_value
diff --git a/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py b/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py
index 58e4559baa..2692ad3aba 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_change_channel_in_promotion_rule.py
@@ -24,20 +24,24 @@ def prepare_promotion(
channel_id=None,
):
promotion_name = "Promotion Test"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_type = "CATALOGUE"
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
promotion_id = promotion_data["id"]
- promotion_rule_data = create_promotion_rule(
- e2e_staff_api_client,
- promotion_id,
- predicate_input,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
- )
- promotion_rule_id = promotion_rule_data["id"]
- discount_value = promotion_rule_data["rewardValue"]
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": predicate_input,
+ "rewardValue": discount_value,
+ "rewardValueType": "PERCENTAGE",
+ }
+
+ promotion_rule = create_promotion_rule(e2e_staff_api_client, input)
+ promotion_rule_id = promotion_rule["id"]
+ discount_value = promotion_rule["rewardValue"]
return promotion_rule_id
diff --git a/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py b/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py
index f049ad152f..001dae24d6 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_change_reward_value_type_in_promotion_rule.py
@@ -16,21 +16,27 @@ def prepare_promotion(
channel_id=None,
):
promotion_name = "Promotion Test"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_type = "CATALOGUE"
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
promotion_id = promotion_data["id"]
predicate_input = {"variantPredicate": {"ids": variant_ids}}
- promotion_rule_data = create_promotion_rule(
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": predicate_input,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
+ promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- predicate_input,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
- promotion_rule_id = promotion_rule_data["id"]
- discount_value = promotion_rule_data["rewardValue"]
+ promotion_rule_id = promotion_rule["id"]
+ discount_value = promotion_rule["rewardValue"]
return promotion_rule_id, discount_value
diff --git a/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py b/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py
index 22f16ecfd5..578270c83f 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_create_promotion_for_collections.py
@@ -95,19 +95,25 @@ def test_create_promotion_for_collection_core_2109(
discount_type = "PERCENTAGE"
promotion_rule_name = "rule for collections"
- promotion_data = create_promotion(e2e_staff_api_client, promotion_name)
+ promotion_type = "CATALOGUE"
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
promotion_id = promotion_data["id"]
collection_ids = [collection_id]
predicate_input = {"collectionPredicate": {"ids": collection_ids}}
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": predicate_input,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ }
promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- predicate_input,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
+ input,
)
collection_predicate = promotion_rule["cataloguePredicate"]["collectionPredicate"]
diff --git a/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py b/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py
index 939c12609e..628020b114 100644
--- a/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py
+++ b/saleor/tests/e2e/promotions/test_staff_can_translate_promotions.py
@@ -27,8 +27,12 @@ def prepare_promotion(
"blocks": [{"data": {"text": "promotion description"}, "type": "paragraph"}],
"version": "1.0.0",
}
+ promotion_type = "CATALOGUE"
promotion_data = create_promotion(
- e2e_staff_api_client, promotion_name, description=promotion_description
+ e2e_staff_api_client,
+ promotion_name,
+ promotion_type,
+ description=promotion_description,
)
promotion_id = promotion_data["id"]
@@ -37,18 +41,21 @@ def prepare_promotion(
"blocks": [{"data": {"text": "rule description"}, "type": "paragraph"}],
"version": "1.0.0",
}
- promotion_rule_data = create_promotion_rule(
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": predicate_input,
+ "rewardValue": discount_value,
+ "rewardValueType": discount_type,
+ "description": rule_description,
+ }
+ promotion_rule = create_promotion_rule(
e2e_staff_api_client,
- promotion_id,
- predicate_input,
- discount_type,
- discount_value,
- promotion_rule_name,
- channel_id,
- description=rule_description,
+ input,
)
- promotion_rule_id = promotion_rule_data["id"]
- discount_value = promotion_rule_data["rewardValue"]
+ promotion_rule_id = promotion_rule["id"]
+ discount_value = promotion_rule["rewardValue"]
return promotion_id, promotion_rule_id
diff --git a/saleor/tests/e2e/promotions/test_unable_to_have_promotion_rule_with_mixed_predicates.py b/saleor/tests/e2e/promotions/test_unable_to_have_promotion_rule_with_mixed_predicates.py
new file mode 100644
index 0000000000..f56d92bf20
--- /dev/null
+++ b/saleor/tests/e2e/promotions/test_unable_to_have_promotion_rule_with_mixed_predicates.py
@@ -0,0 +1,113 @@
+import pytest
+
+from ..product.utils import (
+ create_collection,
+ create_collection_channel_listing,
+)
+from ..shop.utils.preparing_shop import prepare_default_shop
+from ..utils import assign_permissions
+from .utils import create_promotion, raw_create_promotion, raw_update_promotion_rule
+
+
+def prepare_collection(
+ e2e_staff_api_client,
+):
+ shop_data = prepare_default_shop(e2e_staff_api_client)
+ channel_id = shop_data["channel"]["id"]
+
+ collection_data = create_collection(e2e_staff_api_client)
+ collection_id = collection_data["id"]
+
+ create_collection_channel_listing(e2e_staff_api_client, collection_id, channel_id)
+
+ return channel_id, collection_id
+
+
+def test_unable_to_have_promotion_rule_with_mixed_predicates_CORE_2125(
+ e2e_staff_api_client,
+ shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+):
+ # Before
+ permissions = [
+ *shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+ ]
+ assign_permissions(e2e_staff_api_client, permissions)
+
+ (
+ channel_id,
+ collection_id,
+ ) = prepare_collection(
+ e2e_staff_api_client,
+ )
+
+ # Step 1- Create promotion with rule with mixed predicates
+ invalid_promotion_name = "Promotion with mixed predicates"
+ invalid_promotion_type = "CATALOGUE"
+ invalid_promotion_reward_value = "20"
+ invalid_promotion_rules = [
+ {
+ "name": "rule for promotion with mixed predicates",
+ "channels": [channel_id],
+ "cataloguePredicate": {"collectionPredicate": {"ids": [collection_id]}},
+ "orderPredicate": {
+ "discountedObjectPredicate": {"baseTotalPrice": {"eq": "10"}}
+ },
+ "rewardType": "SUBTOTAL_DISCOUNT",
+ "rewardValue": invalid_promotion_reward_value,
+ "rewardValueType": "PERCENTAGE",
+ }
+ ]
+ data = raw_create_promotion(
+ e2e_staff_api_client,
+ invalid_promotion_name,
+ invalid_promotion_type,
+ invalid_promotion_rules,
+ )
+ errors = data["errors"]
+ assert errors[0]["message"] == (
+ "`Order` predicate cannot be provided for promotion rule with "
+ "`catalogue` predicate type."
+ )
+ assert errors[0]["code"] == "INVALID"
+ assert errors[0]["field"] == "orderPredicate"
+
+ # Step 2- Create promotion with rule with order predicate
+ promotion_name = "Promotion"
+ promotion_type = "ORDER"
+ reward_value = "20"
+ rules = [
+ {
+ "name": "rule for promotion with order predicate",
+ "channels": [channel_id],
+ "orderPredicate": {
+ "discountedObjectPredicate": {"baseTotalPrice": {"eq": "10"}}
+ },
+ "rewardType": "SUBTOTAL_DISCOUNT",
+ "rewardValue": reward_value,
+ "rewardValueType": "PERCENTAGE",
+ }
+ ]
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type, rules
+ )
+ promotion_rule_id = promotion_data["rules"][0]["id"]
+
+ # Step 3 - Check the promotion rule cannot be updated with catalogue predicate
+ update_input = {
+ "cataloguePredicate": {"collectionPredicate": {"ids": [collection_id]}}
+ }
+ data = raw_update_promotion_rule(
+ e2e_staff_api_client, promotion_rule_id, update_input
+ )
+ error = data["errors"][0]
+ assert (
+ error["message"]
+ == "`Catalogue` predicate cannot be provided for promotion rule with `order` predicate type."
+ )
+ assert error["code"] == "INVALID"
+ assert error["field"] == "cataloguePredicate"
diff --git a/saleor/tests/e2e/promotions/utils/__init__.py b/saleor/tests/e2e/promotions/utils/__init__.py
index 650b449d12..d1edb84299 100644
--- a/saleor/tests/e2e/promotions/utils/__init__.py
+++ b/saleor/tests/e2e/promotions/utils/__init__.py
@@ -1,16 +1,18 @@
-from .promotion_create import create_promotion
+from .promotion_create import create_promotion, raw_create_promotion
from .promotion_delete import delete_promotion
from .promotion_query import promotion_query
from .promotion_rule_create import create_promotion_rule
from .promotion_rule_translate import translate_promotion_rule
-from .promotion_rule_update import update_promotion_rule
+from .promotion_rule_update import raw_update_promotion_rule, update_promotion_rule
from .promotion_translate import translate_promotion
from .promotions_query import promotions_query
__all__ = [
"create_promotion",
+ "raw_create_promotion",
"create_promotion_rule",
"update_promotion_rule",
+ "raw_update_promotion_rule",
"delete_promotion",
"promotion_query",
"promotions_query",
diff --git a/saleor/tests/e2e/promotions/utils/promotion_create.py b/saleor/tests/e2e/promotions/utils/promotion_create.py
index 8bcaff7cf1..64992ec309 100644
--- a/saleor/tests/e2e/promotions/utils/promotion_create.py
+++ b/saleor/tests/e2e/promotions/utils/promotion_create.py
@@ -11,9 +11,23 @@ mutation CreatePromotion($input: PromotionCreateInput!) {
promotion {
id
name
+ type
startDate
endDate
description
+ rules {
+ orderPredicate
+ name
+ rewardType
+ rewardValue
+ rewardValueType
+ cataloguePredicate
+ channels {
+ id
+ }
+ id
+ description
+ }
createdAt
metadata {
key
@@ -29,9 +43,11 @@ mutation CreatePromotion($input: PromotionCreateInput!) {
"""
-def create_promotion(
+def raw_create_promotion(
staff_api_client,
promotion_name,
+ promotion_type,
+ rules=None,
start_date=None,
end_date=None,
description=None,
@@ -39,12 +55,23 @@ def create_promotion(
variables = {
"input": {
"name": promotion_name,
+ "type": promotion_type,
+ "rules": rules,
"startDate": start_date,
"endDate": end_date,
"description": description,
}
}
+ if rules is not None:
+ variables["input"]["rules"] = rules
+
+ if start_date is not None:
+ variables["input"]["startDate"] = start_date
+
+ if end_date is not None:
+ variables["input"]["endDate"] = end_date
+
response = staff_api_client.post_graphql(
PROMOTION_CREATE_MUTATION,
variables,
@@ -52,8 +79,30 @@ def create_promotion(
content = get_graphql_content(response)
- assert content["data"]["promotionCreate"]["errors"] == []
+ raw_data = content["data"]["promotionCreate"]
+ return raw_data
+
+
+def create_promotion(
+ staff_api_client,
+ promotion_name,
+ promotion_type,
+ rules=None,
+ start_date=None,
+ end_date=None,
+ description=None,
+):
+ response = raw_create_promotion(
+ staff_api_client,
+ promotion_name,
+ promotion_type,
+ rules,
+ start_date,
+ end_date,
+ description,
+ )
- data = content["data"]["promotionCreate"]["promotion"]
+ data = response["promotion"]
+ assert response["errors"] == []
assert data["id"] is not None
return data
diff --git a/saleor/tests/e2e/promotions/utils/promotion_rule_create.py b/saleor/tests/e2e/promotions/utils/promotion_rule_create.py
index 2b8215c94b..01af6d0f45 100644
--- a/saleor/tests/e2e/promotions/utils/promotion_rule_create.py
+++ b/saleor/tests/e2e/promotions/utils/promotion_rule_create.py
@@ -14,7 +14,9 @@ mutation promotionRuleCreate($input: PromotionRuleCreateInput!) {
description
rewardValueType
rewardValue
+ predicateType
cataloguePredicate
+ orderPredicate
channels{
id
}
@@ -24,30 +26,8 @@ mutation promotionRuleCreate($input: PromotionRuleCreateInput!) {
"""
-def create_promotion_rule(
- staff_api_client,
- promotion_id,
- catalogue_predicate,
- reward_value_type="PERCENTAGE",
- reward_value=5.00,
- promotion_rule_name="Test rule",
- channel_id=None,
- description=None,
-):
- if not channel_id:
- channel_id = []
-
- variables = {
- "input": {
- "promotion": promotion_id,
- "name": promotion_rule_name,
- "rewardValueType": reward_value_type,
- "rewardValue": reward_value,
- "channels": channel_id,
- "cataloguePredicate": catalogue_predicate,
- "description": description,
- }
- }
+def create_promotion_rule(staff_api_client, input):
+ variables = {"input": input}
response = staff_api_client.post_graphql(
PROMOTION_RULE_CREATE_MUTATION,
@@ -59,7 +39,5 @@ def create_promotion_rule(
data = content["data"]["promotionRuleCreate"]["promotionRule"]
assert data["id"] is not None
- assert data["name"] == promotion_rule_name
- assert data["rewardValueType"] == reward_value_type
- assert data["rewardValue"] == reward_value
+
return data
diff --git a/saleor/tests/e2e/promotions/utils/promotion_rule_update.py b/saleor/tests/e2e/promotions/utils/promotion_rule_update.py
index 51838d1772..afcd60cd98 100644
--- a/saleor/tests/e2e/promotions/utils/promotion_rule_update.py
+++ b/saleor/tests/e2e/promotions/utils/promotion_rule_update.py
@@ -15,6 +15,7 @@ mutation promotionRuleCreate($id: ID!, $input: PromotionRuleUpdateInput!) {
rewardValueType
rewardValue
cataloguePredicate
+ orderPredicate
channels {
id
}
@@ -24,7 +25,7 @@ mutation promotionRuleCreate($id: ID!, $input: PromotionRuleUpdateInput!) {
"""
-def update_promotion_rule(
+def raw_update_promotion_rule(
staff_api_client,
promotion_rule_id,
input,
@@ -37,7 +38,23 @@ def update_promotion_rule(
)
content = get_graphql_content(response)
- assert content["data"]["promotionRuleUpdate"]["errors"] == []
+ raw_data = content["data"]["promotionRuleUpdate"]
+
+ return raw_data
+
+
+def update_promotion_rule(
+ staff_api_client,
+ promotion_rule_id,
+ input,
+):
+ response = raw_update_promotion_rule(
+ staff_api_client,
+ promotion_rule_id,
+ input,
+ )
+
+ assert response["errors"] == []
- data = content["data"]["promotionRuleUpdate"]["promotionRule"]
+ data = response["promotionRule"]
return data
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 5232d6d62b..acdcc7515b 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -54,11 +54,14 @@ from ..discount import (
DiscountType,
DiscountValueType,
PromotionEvents,
+ PromotionType,
+ RewardType,
RewardValueType,
VoucherType,
)
from ..discount.interface import VariantPromotionRuleInfo
from ..discount.models import (
+ CheckoutDiscount,
CheckoutLineDiscount,
NotApplicable,
Promotion,
@@ -404,6 +407,39 @@ def checkout_with_item_on_promotion(checkout_with_item):
return checkout_with_item
+def checkout_with_item_and_order_discount(
+ checkout_with_item, catalogue_promotion_without_rules
+):
+ channel = checkout_with_item.channel
+
+ reward_value = Decimal("5")
+
+ rule = catalogue_promotion_without_rules.rules.create(
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 20}}}
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel)
+
+ CheckoutDiscount.objects.create(
+ checkout=checkout_with_item,
+ promotion_rule=rule,
+ type=DiscountType.ORDER_PROMOTION,
+ value_type=rule.reward_value_type,
+ value=rule.reward_value,
+ amount_value=rule.reward_value,
+ currency=channel.currency_code,
+ )
+ checkout_with_item.discount_amount = reward_value
+ checkout_with_item.save(update_fields=["discount_amount"])
+
+ return checkout_with_item
+
+
@pytest.fixture
def checkout_with_item_and_transaction_item(checkout_with_item):
TransactionItem.objects.create(
@@ -4151,12 +4187,12 @@ def order_line(order, variant):
@pytest.fixture
-def order_line_on_promotion(order_line, promotion):
+def order_line_on_promotion(order_line, catalogue_promotion):
variant = order_line.variant
channel = order_line.order.channel
reward_value = Decimal("1.0")
- rule = promotion.rules.first()
+ rule = catalogue_promotion.rules.first()
variant_channel_listing = variant.channel_listings.get(channel=channel)
variant_channel_listing.discounted_price_amount = (
@@ -5543,9 +5579,10 @@ def dummy_webhook_app_payment_data(dummy_payment_data, payment_app):
@pytest.fixture
-def promotion(channel_USD, product, collection):
+def catalogue_promotion(channel_USD, product, collection):
promotion = Promotion.objects.create(
name="Promotion",
+ type=PromotionType.CATALOGUE,
description=dummy_editorjs("Test description."),
end_date=timezone.now() + timedelta(days=30),
)
@@ -5588,18 +5625,32 @@ def promotion(channel_USD, product, collection):
@pytest.fixture
-def promotion_without_rules(db):
+def catalogue_promotion_without_rules(db):
+ promotion = Promotion.objects.create(
+ name="Promotion",
+ description=dummy_editorjs("Test description."),
+ end_date=timezone.now() + timedelta(days=30),
+ type=PromotionType.CATALOGUE,
+ )
+ return promotion
+
+
+def order_promotion_without_rules(db):
promotion = Promotion.objects.create(
name="Promotion",
description=dummy_editorjs("Test description."),
end_date=timezone.now() + timedelta(days=30),
+ type=PromotionType.ORDER,
)
return promotion
@pytest.fixture
-def promotion_with_single_rule(catalogue_predicate, channel_USD):
- promotion = Promotion.objects.create(name="Promotion with single rule")
+def catalogue_promotion_with_single_rule(catalogue_predicate, channel_USD):
+ promotion = Promotion.objects.create(
+ name="Promotion with single rule", type=PromotionType.CATALOGUE
+ )
rule = PromotionRule.objects.create(
name="Sale rule",
promotion=promotion,
@@ -5611,6 +5662,25 @@ def promotion_with_single_rule(catalogue_predicate, channel_USD):
return promotion
+def order_promotion_with_rule(channel_USD):
+ promotion = Promotion.objects.create(
+ name="Promotion with order rule", type=PromotionType.ORDER
+ )
+ rule = PromotionRule.objects.create(
+ name="Promotion rule",
+ promotion=promotion,
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal(5),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel_USD)
+ return promotion
+
+
@pytest.fixture
def promotion_list(channel_USD, product, collection):
collection.products.add(product)
@@ -5618,18 +5688,21 @@ def promotion_list(channel_USD, product, collection):
[
Promotion(
name="Promotion 1",
+ type=PromotionType.CATALOGUE,
description=dummy_editorjs("Promotion 1 description."),
start_date=timezone.now() + timedelta(days=1),
end_date=timezone.now() + timedelta(days=10),
),
Promotion(
name="Promotion 2",
+ type=PromotionType.CATALOGUE,
description=dummy_editorjs("Promotion 2 description."),
start_date=timezone.now() + timedelta(days=5),
end_date=timezone.now() + timedelta(days=20),
),
Promotion(
name="Promotion 3",
+ type=PromotionType.CATALOGUE,
description=dummy_editorjs("TePromotion 3 description."),
start_date=timezone.now() + timedelta(days=15),
end_date=timezone.now() + timedelta(days=30),
@@ -5703,10 +5776,10 @@ def promotion_list(channel_USD, product, collection):
@pytest.fixture
-def promotion_rule(channel_USD, promotion, product):
+def promotion_rule(channel_USD, catalogue_promotion, product):
rule = PromotionRule.objects.create(
name="Promotion rule name",
- promotion=promotion,
+ promotion=catalogue_promotion,
description=dummy_editorjs("Test description for percentage promotion rule."),
catalogue_predicate={
"productPredicate": {
@@ -5720,6 +5793,22 @@ def promotion_rule(channel_USD, promotion, product):
return rule
+def order_promotion_rule(channel_USD, order_promotion_without_rules):
+ rule = PromotionRule.objects.create(
+ name="Order promotion rule",
+ promotion=order_promotion_without_rules,
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 20}}}
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal("25"),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel_USD)
+ return rule
+
+
@pytest.fixture
def rule_info(
promotion_rule,
@@ -5761,7 +5850,7 @@ def catalogue_predicate(product, category, collection, variant):
@pytest.fixture
def promotion_converted_from_sale(catalogue_predicate, channel_USD):
- promotion = Promotion.objects.create(name="Sale")
+ promotion = Promotion.objects.create(name="Sale", type=PromotionType.CATALOGUE)
promotion.assign_old_sale_id()
rule = PromotionRule.objects.create(
@@ -5797,7 +5886,9 @@ def promotion_converted_from_sale_with_many_channels(
@pytest.fixture
def promotion_converted_from_sale_with_empty_predicate(channel_USD):
- promotion = Promotion.objects.create(name="Sale with empty predicate")
+ promotion = Promotion.objects.create(
+ name="Sale with empty predicate", type=PromotionType.CATALOGUE
+ )
promotion.assign_old_sale_id()
rule = PromotionRule.objects.create(
name="Sale with empty predicate rule",
@@ -5812,7 +5903,8 @@ def promotion_converted_from_sale_with_empty_predicate(channel_USD):
@pytest.fixture
-def promotion_events(promotion, staff_user):
+def promotion_events(catalogue_promotion, staff_user):
+ promotion = catalogue_promotion
rule_id = promotion.rules.first().pk
events = PromotionEvent.objects.bulk_create(
[
@@ -6498,10 +6590,10 @@ def shipping_method_translation_fr(shipping_method):
@pytest.fixture
-def promotion_translation_fr(promotion):
+def promotion_translation_fr(catalogue_promotion):
return PromotionTranslation.objects.create(
language_code="fr",
- promotion=promotion,
+ promotion=catalogue_promotion,
name="French promotion name",
description=dummy_editorjs("French promotion description."),
)
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 967597b94d..2e06de4347 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -1283,15 +1283,13 @@ def generate_checkout_payload_for_tax_calculation(
user_id = graphene.Node.to_global_id("User", user.id)
user_public_metadata = user.metadata
- # Prepare discount data
- # total_amount include the specific product and apply once per order discounts,
- # so we need to attach only entire order discount here with once per order flag
- # set to False
- discount_not_included = (
- checkout_info.voucher.type == VoucherType.ENTIRE_ORDER
- and checkout_info.voucher.apply_once_per_order is False
- if checkout_info.voucher
- else False
+ # order promotion discount and entire_order voucher discount with
+ # apply_once_per_order set to False is not already included in the total price
+ discounted_object_promotion = bool(checkout_info.discounts)
+ discount_not_included = discounted_object_promotion or (
+ checkout_info.voucher
+ and checkout_info.voucher.type == VoucherType.ENTIRE_ORDER
+ and not checkout_info.voucher.apply_once_per_order
)
discount_amount = quantize_price(checkout.discount_amount, checkout.currency)
discount_name = checkout.discount_name
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 04dc4c9855..c9747df0ff 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -21,6 +21,7 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
from ...core.utils.json_serializer import CustomJsonEncoder
from ...discount import DiscountType, DiscountValueType
+from ...discount.models import CheckoutDiscount
from ...graphql.utils import get_user_or_app_from_context
from ...order import FulfillmentLineData, OrderOrigin
from ...order.actions import fulfill_order_lines
@@ -1839,6 +1840,114 @@ def test_generate_checkout_payload_for_tax_calculation_specific_product_voucher(
)
+@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_order_discount(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ prices_entered_with_tax,
+ order_promotion_rule,
+):
+ checkout = checkout_with_prices
+ rule = order_promotion_rule
+ currency = checkout.currency
+
+ discount_amount = Decimal("5.00")
+ CheckoutDiscount.objects.create(
+ checkout=checkout,
+ promotion_rule=rule,
+ type=DiscountType.ORDER_PROMOTION,
+ value_type=rule.reward_value_type,
+ value=rule.reward_value,
+ amount_value=discount_amount,
+ currency=checkout.currency,
+ )
+
+ checkout.discount_amount = discount_amount
+ checkout.discount_name = rule.name
+ checkout.save(update_fields=["discount_amount", "discount_name"])
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ subtotal_price = Money(0, currency)
+ for line_info in lines:
+ variant = line_info.variant
+ variant_listing = line_info.channel_listing
+ unit_price = variant.get_price(variant_listing)
+ subtotal_price += unit_price * line_info.line.quantity
+ shipping_price = quantize_price(
+ checkout.shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price.amount,
+ currency,
+ )
+ total_price_amount = subtotal_price.amount + shipping_price
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [{"amount": str(discount_amount), "name": rule.name}],
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {"meta_key": "meta_value"},
+ "shipping_name": checkout.shipping_method.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
+ "total_amount": str(
+ quantize_price(
+ total_price_amount,
+ currency,
+ )
+ ),
+ "shipping_amount": str(shipping_price),
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ )
+
+
@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
def test_generate_checkout_payload_for_tax_calculation_digital_checkout(
mocked_serialize_checkout_lines_for_tax_calculation,
diff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.py
index e77f4caf1f..a6661308a3 100644
--- a/saleor/webhook/tests/test_webhook_serializers.py
+++ b/saleor/webhook/tests/test_webhook_serializers.py
@@ -237,10 +237,13 @@ def test_serialize_checkout_lines_with_promotion(checkout_with_item_on_promotion
checkout = checkout_with_item_on_promotion
channel = checkout.channel
checkout_lines, _ = fetch_checkout_lines(checkout, prefetch_variant_attributes=True)
-
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)
variant = checkout_lines[0].variant
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_lines)
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines
+ )
# when
checkout_lines_data = serialize_checkout_lines(checkout)
@@ -353,7 +356,7 @@ def test_serialize_checkout_lines_for_tax_calculation_with_promotion(
lines, _ = fetch_checkout_lines(checkout)
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- create_or_update_discount_objects_from_promotion_for_checkout(lines)
+ create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)
tax_configuration = checkout_info.tax_configuration
tax_configuration.country_exceptions.all().delete()
@@ -400,3 +403,50 @@ def test_serialize_checkout_lines_for_tax_calculation_with_promotion(
assert unit_price < undiscounted_unit_price
assert len(checkout_lines_data) == len(list(lines))
+
+
+def test_serialize_checkout_lines_for_tax_calculation_with_order_discount(
+ checkout_with_item_and_order_discount, product
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ tax_configuration = checkout_info.tax_configuration
+ tax_configuration.country_exceptions.all().delete()
+
+ # when
+ checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
+ checkout_info, lines
+ )
+
+ # then
+ line_info = lines[0]
+ line = line_info.line
+ variant = line.variant
+ product = variant.product
+
+ unit_price = variant.get_price(
+ channel_listing=line_info.channel_listing,
+ )
+ total_price_amount = (unit_price * line.quantity).amount
+
+ line_data = checkout_lines_data[0]
+ # the line data shouldn't include order promotin discount
+ assert line_data == {
+ "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
+ "sku": variant.sku,
+ "quantity": line.quantity,
+ "charge_taxes": tax_configuration.charge_taxes,
+ "full_name": variant.display_product(),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "product_metadata": product.metadata,
+ "product_type_metadata": product.product_type.metadata,
+ "unit_amount": unit_price.amount,
+ "total_amount": total_price_amount,
+ }