Skip to content

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

Cancelling orders (#11960)

Krzysztof Waliczek0b804a02099a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54caded390..a180dacb22 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -127,6 +127,9 @@ All notable, unreleased changes to this project will be documented in this file.
- [Preview] Add `CustomerBulkUpdate` mutation - #12268 by @SzymJ
### Other changes
+- Add celery beat task for expiring unconfirmed not paid orders - #11960 by @kadewu:
+ - Add `expireOrdersAfter` to `orderSettings` for `Channel` type.
+ - Add `ORDER_EXPIRED` webhook triggered when `Order` is marked as expired.
- Create order discounts for all voucher types - #12272 by @IKarbowiak
- Core now supports Dev Containers for local development - #12391 by @patrys
- Use mailhog smtp server on Dev Container - #12402 by @carlosa54
diff --git a/saleor/channel/migrations/0011_channel_expire_orders_after.py b/saleor/channel/migrations/0011_channel_expire_orders_after.py
new file mode 100644
index 0000000000..3dcec3d44a
--- /dev/null
+++ b/saleor/channel/migrations/0011_channel_expire_orders_after.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0010_channel_default_transaction_flow_strategy"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="expire_orders_after",
+ field=models.IntegerField(default=None, null=True, blank=True),
+ ),
+ ]
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index 8d9d720297..a3e2b74339 100644
--- a/saleor/channel/models.py
+++ b/saleor/channel/models.py
@@ -34,6 +34,12 @@ class Channel(models.Model):
default=True,
null=True,
)
+ expire_orders_after = models.IntegerField(default=None, null=True, blank=True)
+ order_mark_as_paid_strategy = models.CharField(
+ max_length=255,
+ choices=MarkAsPaidStrategy.CHOICES,
+ default=MarkAsPaidStrategy.PAYMENT_FLOW,
+ )
class Meta:
ordering = ("slug",)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index fb762b84eb..867e91bc49 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -1121,7 +1121,10 @@ def _create_order_from_checkout(
# status
status = (
OrderStatus.UNFULFILLED
- if checkout_info.channel.automatically_confirm_all_new_orders
+ if (
+ checkout_info.channel.automatically_confirm_all_new_orders
+ and checkout_info.checkout.payment_transactions.exists()
+ )
else OrderStatus.UNCONFIRMED
)
checkout_metadata = get_or_create_checkout_metadata(checkout_info.checkout)
diff --git a/saleor/core/migrations/0006_celerytask.py b/saleor/core/migrations/0006_celerytask.py
new file mode 100644
index 0000000000..1da4ded608
--- /dev/null
+++ b/saleor/core/migrations/0006_celerytask.py
@@ -0,0 +1,44 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("core", "0005_alter_eventdelivery_webhook"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CeleryTask",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("success", "Success"),
+ ("failed", "Failed"),
+ ("deleted", "Deleted"),
+ ],
+ default="pending",
+ max_length=50,
+ ),
+ ),
+ ("message", models.CharField(blank=True, max_length=255, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("name", models.CharField(max_length=255, unique=True)),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ ]
diff --git a/saleor/core/models.py b/saleor/core/models.py
index 086d4b7091..484f56ec7b 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -183,3 +183,7 @@ class EventDeliveryAttempt(models.Model):
class Meta:
ordering = ("-created_at",)
+
+
+class CeleryTask(Job):
+ name = models.CharField(max_length=255, unique=True)
diff --git a/saleor/core/tasks.py b/saleor/core/tasks.py
index 59401971c2..015fb0b27f 100644
--- a/saleor/core/tasks.py
+++ b/saleor/core/tasks.py
@@ -1,3 +1,5 @@
+from contextlib import contextmanager
+
from botocore.exceptions import ClientError
from django.conf import settings
from django.core.files.storage import default_storage
@@ -5,7 +7,30 @@ from django.db.models import Exists, OuterRef, Q
from django.utils import timezone
from ..celeryconf import app
-from .models import EventDelivery, EventDeliveryAttempt, EventPayload
+from .models import CeleryTask, EventDelivery, EventDeliveryAttempt, EventPayload
+
+
+@contextmanager
+def celery_task_lock(task_name: str):
+ """Celery task lock.
+
+ This contextmanager provides lock on database for executing celery task.
+
+ Parameters
+ ----------
+ task_name : str
+ Unique name of the celery task.
+
+ """
+
+ lock = None
+ created = False
+ try:
+ lock, created = CeleryTask.objects.get_or_create(name=task_name)
+ yield lock, created
+ finally:
+ if lock and created:
+ lock.delete()
@app.task
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index 4b198c5537..e6d12f104f 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -1,7 +1,9 @@
import graphene
+from django.core.exceptions import ValidationError
from django.utils.text import slugify
from ....channel import models
+from ....channel.error_codes import ChannelErrorCode
from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ChannelPermissions
from ....tax.models import TaxConfiguration
@@ -21,6 +23,7 @@ from ...core.doc_category import (
DOC_CATEGORY_PRODUCTS,
)
from ...core.mutations import ModelMutation
+from ...core.scalars import Minute
from ...core.types import BaseInputObjectType, ChannelError, NonNullList
from ...plugins.dataloaders import get_plugin_manager_promise
from ..enums import (
@@ -56,6 +59,14 @@ class OrderSettingsInput(BaseInputObjectType):
description="When enabled, all non-shippable gift card orders "
"will be fulfilled automatically. By defualt set to True.",
)
+ expire_orders_after = Minute(
+ required=False,
+ description=(
+ "Expiration time in minutes. "
+ "Default null - means do not expire any orders. "
+ "Enter 0 or null to disable." + ADDED_IN_313 + PREVIEW_FEATURE
+ ),
+ )
mark_as_paid_strategy = MarkAsPaidStrategyEnum(
required=False,
description=(
@@ -165,6 +176,7 @@ class ChannelCreate(ModelMutation):
cleaned_input[
"automatically_confirm_all_new_orders"
] = automatically_confirm_all_new_orders
+
automatically_fulfill_non_shippable_gift_card = order_settings.get(
"automatically_fulfill_non_shippable_gift_card"
)
@@ -175,6 +187,11 @@ class ChannelCreate(ModelMutation):
if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):
cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy
+ if "expire_orders_after" in order_settings:
+ expire_orders_after = order_settings["expire_orders_after"]
+ cleaned_input["expire_orders_after"] = cls.clean_expire_orders_after(
+ expire_orders_after
+ )
if default_transaction_strategy := order_settings.get(
"default_transaction_flow_strategy"
):
@@ -184,6 +201,21 @@ class ChannelCreate(ModelMutation):
return cleaned_input
+ @classmethod
+ def clean_expire_orders_after(cls, expire_orders_after):
+ if expire_orders_after is None or expire_orders_after == 0:
+ return None
+ if expire_orders_after < 0:
+ raise ValidationError(
+ {
+ "expire_orders_after": ValidationError(
+ "Expiration time for orders cannot be lower than 0.",
+ code=ChannelErrorCode.INVALID.value,
+ )
+ }
+ )
+ return expire_orders_after
+
@classmethod
def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):
with traced_atomic_transaction():
diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.py
index 5d97f5da36..b80dfdc8ad 100644
--- a/saleor/graphql/channel/mutations/channel_update.py
+++ b/saleor/graphql/channel/mutations/channel_update.py
@@ -110,6 +110,12 @@ class ChannelUpdate(ModelMutation):
"automatically_fulfill_non_shippable_gift_card"
] = automatically_fulfill_non_shippable_gift_card
+ if "expire_orders_after" in order_settings:
+ expire_orders_after = order_settings["expire_orders_after"]
+ cleaned_input["expire_orders_after"] = cls.clean_expire_orders_after(
+ expire_orders_after
+ )
+
if mark_as_paid_strategy := order_settings.get("mark_as_paid_strategy"):
cleaned_input["order_mark_as_paid_strategy"] = mark_as_paid_strategy
@@ -121,6 +127,21 @@ class ChannelUpdate(ModelMutation):
] = default_transaction_strategy
return cleaned_input
+ @classmethod
+ def clean_expire_orders_after(cls, expire_orders_after):
+ if expire_orders_after is None or expire_orders_after == 0:
+ return None
+ if expire_orders_after < 0:
+ raise ValidationError(
+ {
+ "expire_orders_after": ValidationError(
+ "Expiration time for orders cannot be lower than 0.",
+ code=ChannelErrorCode.INVALID.value,
+ )
+ }
+ )
+ return expire_orders_after
+
@classmethod
def check_permissions(cls, context, permissions=None, **data):
permissions = [ChannelPermissions.MANAGE_CHANNELS]
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.py
index 14192516b7..b23dfc21d1 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -2,6 +2,7 @@ import json
from unittest import mock
import graphene
+import pytest
from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from freezegun import freeze_time
@@ -40,6 +41,7 @@ CHANNEL_CREATE_MUTATION = """
orderSettings {
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
+ expireOrdersAfter
markAsPaidStrategy
defaultTransactionFlowStrategy
}
@@ -74,6 +76,7 @@ def test_channel_create_mutation_as_staff_user(
"orderSettings": {
"automaticallyConfirmAllNewOrders": False,
"automaticallyFulfillNonShippableGiftCard": False,
+ "expireOrdersAfter": 10,
},
}
}
@@ -105,6 +108,7 @@ def test_channel_create_mutation_as_staff_user(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
is False
)
+ assert channel_data["orderSettings"]["expireOrdersAfter"] == 10
def test_channel_create_mutation_as_app(
@@ -155,6 +159,7 @@ def test_channel_create_mutation_as_app(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
is True
)
+ assert channel_data["orderSettings"]["expireOrdersAfter"] is None
def test_channel_create_mutation_as_customer(user_api_client):
@@ -189,6 +194,82 @@ def test_channel_create_mutation_as_customer(user_api_client):
assert_no_permission(response)
+def test_channel_create_mutation_negative_expire_orders(
+ permission_manage_channels,
+ app_api_client,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ default_country = "US"
+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.name
+ variables = {
+ "input": {
+ "name": name,
+ "slug": slug,
+ "currencyCode": currency_code,
+ "defaultCountry": default_country,
+ "stockSettings": {"allocationStrategy": allocation_strategy},
+ "orderSettings": {
+ "expireOrdersAfter": -1,
+ },
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ error = content["data"]["channelCreate"]["errors"][0]
+ assert error["field"] == "expireOrdersAfter"
+ assert error["code"] == ChannelErrorCode.INVALID.name
+
+
[email protected]("expire_input", [0, None])
+def test_channel_create_mutation_disabled_expire_orders(
+ expire_input,
+ permission_manage_channels,
+ app_api_client,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ default_country = "US"
+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.name
+ variables = {
+ "input": {
+ "name": name,
+ "slug": slug,
+ "currencyCode": currency_code,
+ "defaultCountry": default_country,
+ "stockSettings": {"allocationStrategy": allocation_strategy},
+ "orderSettings": {
+ "expireOrdersAfter": expire_input,
+ },
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["channelCreate"]
+ assert not data["errors"]
+ assert data["channel"]["orderSettings"]["expireOrdersAfter"] is None
+
+
def test_channel_create_mutation_as_anonymous(api_client):
# given
name = "testName"
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index 676f27aa29..b0d56f008e 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -39,6 +39,7 @@ CHANNEL_UPDATE_MUTATION = """
orderSettings {
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
+ expireOrdersAfter
markAsPaidStrategy
defaultTransactionFlowStrategy
}
@@ -74,6 +75,7 @@ def test_channel_update_mutation_as_staff_user(
"orderSettings": {
"automaticallyConfirmAllNewOrders": False,
"automaticallyFulfillNonShippableGiftCard": False,
+ "expireOrdersAfter": 10,
},
},
}
@@ -105,6 +107,7 @@ def test_channel_update_mutation_as_staff_user(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
is False
)
+ assert channel_data["orderSettings"]["expireOrdersAfter"] == 10
def test_channel_update_mutation_as_app(
@@ -722,6 +725,71 @@ def test_channel_update_mutation_duplicated_warehouses(
assert errors[0]["warehouses"] == [add_warehouse]
[email protected]("expire_input", [0, None])
+def test_channel_update_mutation_disable_expire_orders(
+ expire_input,
+ permission_manage_channels,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_USD.expire_orders_after = 10
+ channel_USD.save()
+
+ variables = {
+ "id": channel_id,
+ "input": {
+ "orderSettings": {"expireOrdersAfter": expire_input},
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ assert data["channel"]["orderSettings"]["expireOrdersAfter"] is None
+
+ channel_USD.refresh_from_db()
+ assert channel_USD.expire_orders_after is None
+
+
+def test_channel_update_mutation_negative_expire_orders(
+ permission_manage_channels,
+ app_api_client,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {
+ "id": channel_id,
+ "input": {
+ "orderSettings": {"expireOrdersAfter": -1},
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ error = content["data"]["channelUpdate"]["errors"][0]
+ assert error["field"] == "expireOrdersAfter"
+ assert error["code"] == ChannelErrorCode.INVALID.name
+
+
def test_channel_update_order_settings_manage_orders(
permission_manage_orders,
staff_api_client,
@@ -765,6 +833,9 @@ def test_channel_update_order_settings_empty_order_settings(
):
# given
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_USD.expire_orders_after = 10
+ channel_USD.save()
+
variables = {
"id": channel_id,
"input": {
@@ -789,6 +860,12 @@ def test_channel_update_order_settings_empty_order_settings(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
is True
)
+ assert channel_data["orderSettings"]["expireOrdersAfter"] == 10
+
+ channel_USD.refresh_from_db()
+ assert channel_USD.automatically_confirm_all_new_orders is True
+ assert channel_USD.automatically_fulfill_non_shippable_gift_card is True
+ assert channel_USD.expire_orders_after == 10
def test_channel_update_order_settings_manage_orders_as_app(
diff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.py
index 1381e7f63e..1d62df4a5d 100644
--- a/saleor/graphql/channel/tests/queries/test_channel.py
+++ b/saleor/graphql/channel/tests/queries/test_channel.py
@@ -288,6 +288,7 @@ QUERY_CHANNEL_ORDER_SETTINGS = """
orderSettings {
automaticallyConfirmAllNewOrders
automaticallyFulfillNonShippableGiftCard
+ expireOrdersAfter
markAsPaidStrategy
defaultTransactionFlowStrategy
}
@@ -330,6 +331,10 @@ def test_query_channel_order_settings_as_staff_user(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
== channel_USD.automatically_fulfill_non_shippable_gift_card
)
+ assert (
+ channel_data["orderSettings"]["expireOrdersAfter"]
+ == channel_USD.expire_orders_after
+ )
assert (
channel_data["orderSettings"]["defaultTransactionFlowStrategy"]
== channel_USD.default_transaction_flow_strategy.upper()
@@ -372,6 +377,10 @@ def test_query_channel_order_settings_as_app(
channel_data["orderSettings"]["automaticallyFulfillNonShippableGiftCard"]
== channel_USD.automatically_fulfill_non_shippable_gift_card
)
+ assert (
+ channel_data["orderSettings"]["expireOrdersAfter"]
+ == channel_USD.expire_orders_after
+ )
assert (
channel_data["orderSettings"]["defaultTransactionFlowStrategy"]
== channel_USD.default_transaction_flow_strategy.upper()
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 3c92382c5b..dc67f9f9e1 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -25,6 +25,7 @@ from ..core.descriptions import (
PREVIEW_FEATURE,
)
from ..core.fields import PermissionsField
+from ..core.scalars import Minute
from ..core.types import CountryDisplay, ModelObjectType, NonNullList
from ..meta.types import ObjectWithMetadata
from ..translations.resolvers import resolve_translation
@@ -182,6 +183,14 @@ class OrderSettings(ObjectType):
"will be fulfilled automatically."
),
)
+ expire_orders_after = Minute(
+ required=False,
+ description=(
+ "Expiration time in minutes. Default null - means do not expire any orders."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ )
mark_as_paid_strategy = MarkAsPaidStrategyEnum(
required=True,
@@ -451,6 +460,7 @@ class Channel(ModelObjectType):
automatically_fulfill_non_shippable_gift_card=(
root.automatically_fulfill_non_shippable_gift_card
),
+ expire_orders_after=root.expire_orders_after,
mark_as_paid_strategy=root.order_mark_as_paid_strategy,
default_transaction_flow_strategy=root.default_transaction_flow_strategy,
)
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 6dcdb57c6b..dac95fa229 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
@@ -164,7 +164,7 @@ def test_order_from_checkout(
order_token = data["order"]["token"]
assert Order.objects.count() == orders_count + 1
order = Order.objects.first()
- assert order.status == OrderStatus.UNFULFILLED
+ assert order.status == OrderStatus.UNCONFIRMED
assert order.origin == OrderOrigin.CHECKOUT
assert not order.original
assert str(order.pk) == order_token
@@ -207,6 +207,93 @@ def test_order_from_checkout(
_recalculate_order_prices_mock.assert_not_called()
+def test_order_from_checkout_with_transaction(
+ app_api_client,
+ site_settings,
+ checkout_with_item_and_transaction_item,
+ permission_handle_checkouts,
+ permission_manage_checkouts,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_item_and_transaction_item
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = True
+ channel.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.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+ assert not order.original
+
+
+ "auto_confirm, order_status",
+ [(True, OrderStatus.UNFULFILLED), (False, OrderStatus.UNCONFIRMED)],
+)
+def test_order_from_checkout_auto_confirm_flag(
+ auto_confirm,
+ order_status,
+ app_api_client,
+ site_settings,
+ checkout_with_item_and_transaction_item,
+ permission_handle_checkouts,
+ permission_manage_checkouts,
+ address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_item_and_transaction_item
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ channel = checkout.channel
+ channel.automatically_confirm_all_new_orders = auto_confirm
+ channel.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
+ get_graphql_content(response)
+
+ order = Order.objects.first()
+ assert order.status == order_status
+
+
@pytest.mark.integration
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_order_from_checkout_with_metadata(
@@ -266,7 +353,7 @@ def test_order_from_checkout_with_metadata(
order_token = data["order"]["token"]
assert Order.objects.count() == orders_count + 1
order = Order.objects.first()
- assert order.status == OrderStatus.UNFULFILLED
+ assert order.status == OrderStatus.UNCONFIRMED
assert order.origin == OrderOrigin.CHECKOUT
assert not order.original
assert str(order.pk) == order_token
@@ -469,7 +556,7 @@ def test_order_from_checkout_with_variant_without_sku(
order_token = data["order"]["token"]
assert Order.objects.count() == orders_count + 1
order = Order.objects.get(pk=order_token)
- assert order.status == OrderStatus.UNFULFILLED
+ assert order.status == OrderStatus.UNCONFIRMED
assert order.origin == OrderOrigin.CHECKOUT
order_line = order.lines.first()
@@ -1367,7 +1454,7 @@ def test_order_from_draft_create_with_preorder_variant(
order_token = data["order"]["token"]
assert Order.objects.count() == orders_count + 1
order = Order.objects.first()
- assert order.status == OrderStatus.UNFULFILLED
+ assert order.status == OrderStatus.UNCONFIRMED
assert order.origin == OrderOrigin.CHECKOUT
assert not order.original
assert str(order.pk) == order_token
diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.py
index c33621ee6b..75dd2545c1 100644
--- a/saleor/graphql/core/scalars.py
+++ b/saleor/graphql/core/scalars.py
@@ -152,3 +152,7 @@ class Date(graphene.Date):
if isinstance(value, string_types) and not value:
return None
return super(Date, Date).parse_value(value)
+
+
+class Minute(graphene.Int):
+ """The `Minute` scalar type represents number of minutes by integer value."""
diff --git a/saleor/graphql/invoice/mutations.py b/saleor/graphql/invoice/mutations.py
index f0b5ad6d37..485abca2e1 100644
--- a/saleor/graphql/invoice/mutations.py
+++ b/saleor/graphql/invoice/mutations.py
@@ -43,11 +43,12 @@ class InvoiceRequest(ModelMutation):
@staticmethod
def clean_order(order):
- if order.is_draft() or order.is_unconfirmed():
+ if order.is_draft() or order.is_unconfirmed() or order.is_expired():
raise ValidationError(
{
"orderId": ValidationError(
- "Cannot request an invoice for draft or unconfirmed order.",
+ "Cannot request an invoice for draft, "
+ "unconfirmed or expired order.",
code=InvoiceErrorCode.INVALID_STATUS.value,
)
}
@@ -150,11 +151,12 @@ class InvoiceCreate(ModelMutation):
@classmethod
def clean_order(cls, info: ResolveInfo, order):
- if order.is_draft() or order.is_unconfirmed():
+ if order.is_draft() or order.is_unconfirmed() or order.is_expired():
raise ValidationError(
{
"orderId": ValidationError(
- "Cannot create an invoice for draft or unconfirmed order.",
+ "Cannot create an invoice for draft, "
+ "unconfirmed or expired order.",
code=InvoiceErrorCode.INVALID_STATUS.value,
)
}
diff --git a/saleor/graphql/invoice/tests/test_invoice_create.py b/saleor/graphql/invoice/tests/test_invoice_create.py
index 78ac82e1bd..7ce8e5f45a 100644
--- a/saleor/graphql/invoice/tests/test_invoice_create.py
+++ b/saleor/graphql/invoice/tests/test_invoice_create.py
@@ -94,7 +94,9 @@ def test_create_invoice_no_billing_address(
assert not order.events.filter(type=OrderEvents.INVOICE_GENERATED).exists()
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+ "status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED, OrderStatus.EXPIRED)
+)
def test_create_invoice_invalid_order_status(
status, staff_api_client, permission_manage_orders, order
):
diff --git a/saleor/graphql/invoice/tests/test_invoice_request.py b/saleor/graphql/invoice/tests/test_invoice_request.py
index f8acd354ab..af3d09f977 100644
--- a/saleor/graphql/invoice/tests/test_invoice_request.py
+++ b/saleor/graphql/invoice/tests/test_invoice_request.py
@@ -85,7 +85,9 @@ def test_invoice_request(
).exists()
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+ "status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED, OrderStatus.EXPIRED)
+)
def test_invoice_request_invalid_order_status(
status, staff_api_client, permission_manage_orders, order
):
diff --git a/saleor/graphql/order/resolvers.py b/saleor/graphql/order/resolvers.py
index 5f712027f4..5e36e42359 100644
--- a/saleor/graphql/order/resolvers.py
+++ b/saleor/graphql/order/resolvers.py
@@ -43,7 +43,7 @@ def resolve_orders_total(info, period, channel_slug):
qs = (
models.Order.objects.using(database_connection_name)
.non_draft()
- .exclude(status=OrderStatus.CANCELED)
+ .exclude(status__in=[OrderStatus.CANCELED, OrderStatus.EXPIRED])
.filter(channel__slug=str(channel_slug))
)
qs = filter_by_period(qs, period, "created_at")
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
index a2728f6d24..55b2b278eb 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_delete.py
@@ -60,6 +60,7 @@ def test_draft_order_delete_product(
OrderStatus.FULFILLED,
OrderStatus.PARTIALLY_RETURNED,
OrderStatus.RETURNED,
+ OrderStatus.EXPIRED,
],
)
def test_draft_order_delete_non_draft_order(
diff --git a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
index e6b7ea05cc..feb032e05d 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
@@ -227,6 +227,7 @@ def test_order_update_shipping_shipping_required(
OrderStatus.PARTIALLY_RETURNED,
OrderStatus.RETURNED,
OrderStatus.CANCELED,
+ OrderStatus.EXPIRED,
],
)
def test_order_update_shipping_not_editable_order(
diff --git a/saleor/graphql/order/tests/test_order_clean.py b/saleor/graphql/order/tests/test_order_clean.py
index 8b75a7aade..fa19ae4c0c 100644
--- a/saleor/graphql/order/tests/test_order_clean.py
+++ b/saleor/graphql/order/tests/test_order_clean.py
@@ -59,6 +59,21 @@ def test_clean_order_cancel_draft_order(
)
+def test_clean_order_cancel_expired_order(
+ fulfilled_order_with_all_cancelled_fulfillments,
+):
+ order = fulfilled_order_with_all_cancelled_fulfillments
+
+ order.status = OrderStatus.EXPIRED
+ order.save()
+
+ with pytest.raises(ValidationError) as e:
+ clean_order_cancel(order)
+ assert (
+ e.value.error_dict["order"][0].code == OrderErrorCode.CANNOT_CANCEL_ORDER.value
+ )
+
+
def test_clean_order_cancel_canceled_order(
fulfilled_order_with_all_cancelled_fulfillments,
):
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 6da1e098c9..c1588b6ba3 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -27,6 +27,7 @@ from ...core.exceptions import PermissionDenied
from ...core.tracing import traced_atomic_transaction
from ...core.utils import get_client_ip
from ...core.utils.url import validate_storefront_url
+from ...order import OrderStatus
from ...order import models as order_models
from ...order.events import transaction_event as order_transaction_event
from ...order.models import Order
@@ -993,6 +994,33 @@ class TransactionCreate(BaseMutation):
return name
return ""
+ @classmethod
+ def update_order(
+ cls, order: order_models.Order, money_data: dict, *args, **kwargs
+ ) -> None:
+ update_fields = []
+ if money_data:
+ update_order_search_vector(order, save=False)
+ updates_amounts_for_order(order, save=False)
+ update_fields.extend(
+ [
+ "total_charged_amount",
+ "charge_status",
+ "total_authorized_amount",
+ "authorize_status",
+ "search_vector",
+ ]
+ )
+ if (
+ order.channel.automatically_confirm_all_new_orders
+ and order.status == OrderStatus.UNCONFIRMED
+ ):
+ order.status = OrderStatus.UNFULFILLED
+ update_fields.append("status")
+ if update_fields:
+ update_fields.append("updated_at")
+ order.save(update_fields=update_fields)
+
@classmethod
def perform_mutation( # type: ignore[override]
cls,
@@ -1038,18 +1066,7 @@ class TransactionCreate(BaseMutation):
recalculate_transaction_amounts(new_transaction)
if transaction_data.get("order_id") and money_data:
order = cast(order_models.Order, new_transaction.order)
- update_order_search_vector(order, save=False)
- updates_amounts_for_order(order, save=False)
- order.save(
- update_fields=[
- "total_charged_amount",
- "charge_status",
- "updated_at",
- "total_authorized_amount",
- "authorize_status",
- "search_vector",
- ]
- )
+ cls.update_order(order, money_data)
if transaction_data.get("checkout_id") and money_data:
discounts = load_discounts(info.context)
manager = get_plugin_manager_promise(info.context).get()
@@ -1208,7 +1225,12 @@ class TransactionUpdate(TransactionCreate):
@classmethod
def update_order(
- cls, order: "Order", money_data: dict, psp_reference: Optional[str]
+ cls,
+ order: "Order",
+ money_data: dict,
+ psp_reference: Optional[str] = None,
+ *args,
+ **kwargs
) -> None:
update_fields = []
if money_data:
@@ -1226,6 +1248,12 @@ class TransactionUpdate(TransactionCreate):
update_fields.append(
"search_vector",
)
+ if (
+ order.channel.automatically_confirm_all_new_orders
+ and order.status == OrderStatus.UNCONFIRMED
+ ):
+ order.status = OrderStatus.UNFULFILLED
+ update_fields.append("status")
if update_fields:
update_fields.append("updated_at")
order.save(update_fields=update_fields)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 84d59c025b..2094491d63 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -7,7 +7,7 @@ from mock import patch
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....order import OrderAuthorizeStatus, OrderEvents
+from .....order import OrderAuthorizeStatus, OrderEvents, OrderStatus
from .....order.utils import update_order_authorize_data, update_order_charge_data
from .....payment import TransactionEventStatus, TransactionEventType
from .....payment.error_codes import TransactionCreateErrorCode
@@ -1594,6 +1594,58 @@ def test_creates_transaction_event_for_checkout_by_staff(
assert event.type == TransactionEventType.INFO
+def test_creates_transaction_automatically_confirm(
+ order_with_lines, permission_manage_payments, app_api_client
+):
+ # given
+ order_with_lines.status = OrderStatus.UNCONFIRMED
+ order_with_lines.save()
+ order_with_lines.channel.automatically_confirm_all_new_orders = True
+ order_with_lines.channel.save()
+
+ status = "Failed authorized for 10$"
+ type = "Credit Card"
+ reference = "PSP reference - 123"
+ available_actions = []
+ authorized_value = Decimal("0")
+ metadata = {"key": "test-1", "value": "123"}
+ private_metadata = {"key": "test-2", "value": "321"}
+
+ event_reference = "PSP-ref"
+ event_name = "Test"
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": status,
+ "type": type,
+ "reference": reference,
+ "availableActions": available_actions,
+ "amountAuthorized": {
+ "amount": authorized_value,
+ "currency": "USD",
+ },
+ "metadata": [metadata],
+ "privateMetadata": [private_metadata],
+ },
+ "transaction_event": {
+ "status": TransactionEventStatusEnum.SUCCESS.name,
+ "reference": event_reference,
+ "name": event_name,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+
+ order_with_lines.refresh_from_db()
+ assert order_with_lines.status == OrderStatus.UNFULFILLED
+
+
def test_transaction_create_external_url_incorrect_url_format_by_app(
order_with_lines, permission_manage_payments, app_api_client
):
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 0a42aee22f..ea59d6b487 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -168,7 +168,7 @@ def resolve_report_product_sales(period, channel_slug) -> ChannelQsContext:
# filter by channel and order status
channels = Channel.objects.filter(slug=channel_slug).values("pk")
- exclude_status = [OrderStatus.DRAFT, OrderStatus.CANCELED]
+ exclude_status = [OrderStatus.DRAFT, OrderStatus.CANCELED, OrderStatus.EXPIRED]
orders = Order.objects.exclude(status__in=exclude_status).filter(
Exists(channels.filter(pk=OuterRef("channel_id")).values("pk"))
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 2bb80f00f7..8302b4881c 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1783,6 +1783,9 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""An order is cancelled."""
ORDER_CANCELLED
+ """An order is expired."""
+ ORDER_EXPIRED
+
"""An order is fulfilled."""
ORDER_FULFILLED
@@ -2398,6 +2401,9 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
"""An order is cancelled."""
ORDER_CANCELLED
+ """An order is expired."""
+ ORDER_EXPIRED
+
"""An order is fulfilled."""
ORDER_FULFILLED
@@ -3221,6 +3227,7 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
ORDER_FULLY_PAID
ORDER_UPDATED
ORDER_CANCELLED
+ ORDER_EXPIRED
ORDER_FULFILLED
ORDER_METADATA_UPDATED
DRAFT_ORDER_CREATED
@@ -5080,6 +5087,15 @@ type OrderSettings {
"""
automaticallyFulfillNonShippableGiftCard: Boolean!
+ """
+ Expiration time in minutes. Default null - means do not expire any orders.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ expireOrdersAfter: Minute
+
"""
Determine what strategy will be used to mark the order as paid. Based on the chosen option, the proper object will be created and attached to the order when it's manually marked as paid.
`PAYMENT_FLOW` - [default option] creates the `Payment` object.
@@ -5101,6 +5117,11 @@ type OrderSettings {
defaultTransactionFlowStrategy: TransactionFlowStrategyEnum!
}
+"""
+The `Minute` scalar type represents number of minutes by integer value.
+"""
+scalar Minute
+
"""
Determine the mark as paid strategy for the channel.
@@ -10428,6 +10449,7 @@ enum OrderStatus @doc(category: "Orders") {
RETURNED
FULFILLED
CANCELED
+ EXPIRED
}
"""Represents order fulfillment."""
@@ -11124,6 +11146,7 @@ enum OrderEventsEnum @doc(category: "Orders") {
PLACED_FROM_DRAFT
OVERSOLD_ITEMS
CANCELED
+ EXPIRED
ORDER_MARKED_AS_PAID
ORDER_FULLY_PAID
ORDER_REPLACEMENT_CREATED
@@ -24355,6 +24378,15 @@ input OrderSettingsInput @doc(category: "Orders") {
"""
automaticallyFulfillNonShippableGiftCard: Boolean
+ """
+ Expiration time in minutes. Default null - means do not expire any orders. Enter 0 or null to disable.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ expireOrdersAfter: Minute
+
"""
Determine what strategy will be used to mark the order as paid. Based on the chosen option, the proper object will be created and attached to the order when it's manually marked as paid.
`PAYMENT_FLOW` - [default option] creates the `Payment` object.
@@ -27003,6 +27035,30 @@ type OrderCancelled implements Event @doc(category: "Orders") {
order: Order
}
+"""
+Event sent when order becomes expired.
+
+Added in Saleor 3.13.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type OrderExpired implements Event @doc(category: "Orders") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The order the event relates to."""
+ order: Order
+}
+
"""
Event sent when order metadata is updated.
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index f3c808a741..f27a5a94ab 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -91,6 +91,7 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.ORDER_FULLY_PAID: order_fully_paid_event_enum_description,
WebhookEventAsyncType.ORDER_UPDATED: order_updated_event_enum_description,
WebhookEventAsyncType.ORDER_CANCELLED: "An order is cancelled.",
+ WebhookEventAsyncType.ORDER_EXPIRED: "An order is expired.",
WebhookEventAsyncType.ORDER_FULFILLED: "An order is fulfilled.",
WebhookEventAsyncType.ORDER_METADATA_UPDATED: (
"An order metadata is updated." + ADDED_IN_38 + PREVIEW_FEATURE
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 1fddfc7893..5982eb1271 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -468,6 +468,16 @@ class OrderCancelled(SubscriptionObjectType, OrderBase):
)
+class OrderExpired(SubscriptionObjectType, OrderBase):
+ class Meta:
+ root_type = "Order"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = (
+ "Event sent when order becomes expired." + ADDED_IN_313 + PREVIEW_FEATURE
+ )
+
+
class OrderMetadataUpdated(SubscriptionObjectType, OrderBase):
class Meta:
root_type = "Order"
@@ -2183,6 +2193,7 @@ WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.ORDER_FULLY_PAID: OrderFullyPaid,
WebhookEventAsyncType.ORDER_FULFILLED: OrderFulfilled,
WebhookEventAsyncType.ORDER_CANCELLED: OrderCancelled,
+ WebhookEventAsyncType.ORDER_EXPIRED: OrderExpired,
WebhookEventAsyncType.ORDER_METADATA_UPDATED: OrderMetadataUpdated,
WebhookEventAsyncType.DRAFT_ORDER_CREATED: DraftOrderCreated,
WebhookEventAsyncType.DRAFT_ORDER_UPDATED: DraftOrderUpdated,
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
index 0c117daa40..d5f7537fc4 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
@@ -253,6 +253,7 @@ def async_subscription_webhooks_with_root_objects(
subscription_order_confirmed_webhook,
subscription_order_fully_paid_webhook,
subscription_order_cancelled_webhook,
+ subscription_order_expired_webhook,
subscription_order_fulfilled_webhook,
subscription_order_metadata_updated_webhook,
subscription_draft_order_created_webhook,
@@ -398,6 +399,7 @@ def async_subscription_webhooks_with_root_objects(
events.ORDER_FULLY_PAID: [subscription_order_fully_paid_webhook, order],
events.ORDER_FULFILLED: [subscription_order_fulfilled_webhook, order],
events.ORDER_CANCELLED: [subscription_order_cancelled_webhook, order],
+ events.ORDER_EXPIRED: [subscription_order_expired_webhook, order],
events.ORDER_METADATA_UPDATED: [
subscription_order_metadata_updated_webhook,
order,
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 85e6855ce1..39612b423f 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -21,6 +21,7 @@ class OrderStatus:
)
RETURNED = "returned" # order with all items marked as returned
CANCELED = "canceled" # permanently canceled order
+ EXPIRED = "expired" # order marked as expired
CHOICES = [
(DRAFT, "Draft"),
@@ -31,6 +32,7 @@ class OrderStatus:
(RETURNED, "Returned"),
(FULFILLED, "Fulfilled"),
(CANCELED, "Canceled"),
+ (EXPIRED, "Expired"),
]
@@ -88,6 +90,7 @@ class OrderEvents:
OVERSOLD_ITEMS = "oversold_items"
CANCELED = "canceled"
+ EXPIRED = "expired"
ORDER_MARKED_AS_PAID = "order_marked_as_paid"
ORDER_FULLY_PAID = "order_fully_paid"
@@ -150,6 +153,7 @@ class OrderEvents:
(PLACED_FROM_DRAFT, "The draft order was placed"),
(OVERSOLD_ITEMS, "The draft order was placed with oversold items"),
(CANCELED, "The order was canceled"),
+ (EXPIRED, "The order was automatically expired"),
(ORDER_MARKED_AS_PAID, "The order was manually marked as fully paid"),
(ORDER_FULLY_PAID, "The order was fully paid"),
(ORDER_REPLACEMENT_CREATED, "The draft order was created based on this order."),
diff --git a/saleor/order/migrations/0164_auto_20230329_1200.py b/saleor/order/migrations/0164_auto_20230329_1200.py
new file mode 100644
index 0000000000..478cbe2e0f
--- /dev/null
+++ b/saleor/order/migrations/0164_auto_20230329_1200.py
@@ -0,0 +1,94 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0163_order_events_rename_transaction_events"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="order",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("draft", "Draft"),
+ ("unconfirmed", "Unconfirmed"),
+ ("unfulfilled", "Unfulfilled"),
+ ("partially fulfilled", "Partially fulfilled"),
+ ("partially_returned", "Partially returned"),
+ ("returned", "Returned"),
+ ("fulfilled", "Fulfilled"),
+ ("canceled", "Canceled"),
+ ("expired", "Expired"),
+ ],
+ default="unfulfilled",
+ max_length=32,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orderevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("DRAFT_CREATED", "draft_created"),
+ ("DRAFT_CREATED_FROM_REPLACE", "draft_created_from_replace"),
+ ("ADDED_PRODUCTS", "added_products"),
+ ("REMOVED_PRODUCTS", "removed_products"),
+ ("PLACED", "placed"),
+ ("PLACED_FROM_DRAFT", "placed_from_draft"),
+ ("OVERSOLD_ITEMS", "oversold_items"),
+ ("CANCELED", "canceled"),
+ ("EXPIRED", "expired"),
+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),
+ ("ORDER_FULLY_PAID", "order_fully_paid"),
+ ("ORDER_REPLACEMENT_CREATED", "order_replacement_created"),
+ ("ORDER_DISCOUNT_ADDED", "order_discount_added"),
+ (
+ "ORDER_DISCOUNT_AUTOMATICALLY_UPDATED",
+ "order_discount_automatically_updated",
+ ),
+ ("ORDER_DISCOUNT_UPDATED", "order_discount_updated"),
+ ("ORDER_DISCOUNT_DELETED", "order_discount_deleted"),
+ ("ORDER_LINE_DISCOUNT_UPDATED", "order_line_discount_updated"),
+ ("ORDER_LINE_DISCOUNT_REMOVED", "order_line_discount_removed"),
+ ("ORDER_LINE_PRODUCT_DELETED", "order_line_product_deleted"),
+ ("ORDER_LINE_VARIANT_DELETED", "order_line_variant_deleted"),
+ ("UPDATED_ADDRESS", "updated_address"),
+ ("EMAIL_SENT", "email_sent"),
+ ("CONFIRMED", "confirmed"),
+ ("PAYMENT_AUTHORIZED", "payment_authorized"),
+ ("PAYMENT_CAPTURED", "payment_captured"),
+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),
+ ("PAYMENT_REFUNDED", "payment_refunded"),
+ ("PAYMENT_VOIDED", "payment_voided"),
+ ("PAYMENT_FAILED", "payment_failed"),
+ ("TRANSACTION_EVENT", "transaction_event"),
+ ("TRANSACTION_CHARGE_REQUESTED", "transaction_charge_requested"),
+ ("TRANSACTION_CAPTURE_REQUESTED", "transaction_capture_requested"),
+ ("TRANSACTION_REFUND_REQUESTED", "transaction_refund_requested"),
+ ("TRANSACTION_VOID_REQUESTED", "transaction_void_requested"),
+ ("TRANSACTION_CANCEL_REQUESTED", "transaction_cancel_requested"),
+ (
+ "TRANSACTION_MARK_AS_PAID_FAILED",
+ "transaction_mark_as_paid_failed",
+ ),
+ ("INVOICE_REQUESTED", "invoice_requested"),
+ ("INVOICE_GENERATED", "invoice_generated"),
+ ("INVOICE_UPDATED", "invoice_updated"),
+ ("INVOICE_SENT", "invoice_sent"),
+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),
+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),
+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),
+ ("FULFILLMENT_REFUNDED", "fulfillment_refunded"),
+ ("FULFILLMENT_RETURNED", "fulfillment_returned"),
+ ("FULFILLMENT_REPLACED", "fulfillment_replaced"),
+ ("FULFILLMENT_AWAITS_APPROVAL", "fulfillment_awaits_approval"),
+ ("TRACKING_UPDATED", "tracking_updated"),
+ ("NOTE_ADDED", "note_added"),
+ ("OTHER", "other"),
+ ],
+ max_length=255,
+ ),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 231278cc14..a27b55bb3c 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -85,7 +85,9 @@ class OrderQueryset(models.QuerySet["Order"]):
is_active=True, charge_status=ChargeStatus.NOT_CHARGED
).values("id")
qs = self.filter(Exists(payments.filter(order_id=OuterRef("id"))))
- return qs.exclude(status={OrderStatus.DRAFT, OrderStatus.CANCELED})
+ return qs.exclude(
+ status={OrderStatus.DRAFT, OrderStatus.CANCELED, OrderStatus.EXPIRED}
+ )
def ready_to_confirm(self):
"""Return unconfirmed orders."""
@@ -407,6 +409,9 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
def is_unconfirmed(self):
return self.status == OrderStatus.UNCONFIRMED
+ def is_expired(self):
+ return self.status == OrderStatus.EXPIRED
+
def is_open(self):
statuses = {OrderStatus.UNFULFILLED, OrderStatus.PARTIALLY_FULFILLED}
return self.status in statuses
@@ -423,14 +428,22 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
not self.fulfillments.exclude(
status__in=statuses_allowed_to_cancel
).exists()
- ) and self.status not in {OrderStatus.CANCELED, OrderStatus.DRAFT}
+ ) and self.status not in {
+ OrderStatus.CANCELED,
+ OrderStatus.DRAFT,
+ OrderStatus.EXPIRED,
+ }
def can_capture(self, payment=None):
if not payment:
payment = self.get_last_payment()
if not payment:
return False
- order_status_ok = self.status not in {OrderStatus.DRAFT, OrderStatus.CANCELED}
+ order_status_ok = self.status not in {
+ OrderStatus.DRAFT,
+ OrderStatus.CANCELED,
+ OrderStatus.EXPIRED,
+ }
return payment.can_capture() and order_status_ok
def can_void(self, payment=None):
diff --git a/saleor/order/tasks.py b/saleor/order/tasks.py
index e7012600fa..6760fa1e11 100644
--- a/saleor/order/tasks.py
+++ b/saleor/order/tasks.py
@@ -1,10 +1,29 @@
+import logging
+from datetime import timedelta
from typing import List
+from celery.exceptions import SoftTimeLimitExceeded
+from django.db.models import Exists, F, Func, OuterRef, Subquery, Value
+from django.utils import timezone
+
from ..celeryconf import app
+from ..channel.models import Channel
+from ..core.tasks import celery_task_lock
+from ..core.tracing import traced_atomic_transaction
+from ..core.utils.events import call_event
+from ..discount.models import Voucher, VoucherCustomer
+from ..payment.models import Payment, TransactionItem
from ..plugins.manager import get_plugins_manager
-from .models import Order
+from ..warehouse.management import deallocate_stock_for_orders
+from . import OrderEvents, OrderStatus
+from .models import Order, OrderEvent
from .utils import invalidate_order_prices
+logger = logging.getLogger(__name__)
+
+# Batch size of 100 is about ~87MB of memory usage in task
+ORDER_BATCH_SIZE = 100
+
@app.task
def recalculate_orders_task(order_ids: List[int]):
@@ -21,3 +40,105 @@ def send_order_updated(order_ids):
manager = get_plugins_manager()
for order in Order.objects.filter(id__in=order_ids):
manager.order_updated(order)
+
+
+def _batch_ids(iterable, batch_size=1):
+ length = len(iterable)
+ for index in range(0, length, batch_size):
+ yield iterable[index : min(index + batch_size, length)]
+
+
+def _queryset_in_batches(queryset):
+ ids = queryset.values_list("id", flat=True)
+ for ids_batch in _batch_ids(ids, ORDER_BATCH_SIZE):
+ yield ids_batch
+
+
+def _bulk_release_voucher_usage(order_ids):
+ voucher_orders = Order.objects.filter(
+ voucher=OuterRef("pk"),
+ id__in=order_ids,
+ )
+ count_orders = voucher_orders.annotate(
+ count=Func(F("pk"), function="Count")
+ ).values("count")
+
+ Voucher.objects.filter(
+ Exists(voucher_orders),
+ usage_limit__isnull=False,
+ ).annotate(
+ order_count=Subquery(count_orders)
+ ).update(used=F("used") - F("order_count"))
+
+ voucher_customer_orders = Order.objects.filter(
+ voucher=OuterRef("voucher__id"),
+ user_email=OuterRef("customer_email"),
+ id__in=order_ids,
+ )
+
+ VoucherCustomer.objects.filter(Exists(voucher_customer_orders)).delete()
+
+
+def _call_expired_order_events(order_ids, manager):
+ orders = Order.objects.filter(id__in=order_ids)
+ for order in orders:
+ call_event(manager.order_expired, order)
+ call_event(manager.order_updated, order)
+
+
+def _order_expired_events(order_ids):
+ OrderEvent.objects.bulk_create(
+ [
+ OrderEvent(
+ order_id=order_id,
+ type=OrderEvents.EXPIRED,
+ )
+ for order_id in order_ids
+ ]
+ )
+
+
+def _expire_orders(manager, now):
+ time_diff_func_in_minutes = (
+ Func(Value("day"), now - OuterRef("created_at"), function="DATE_PART") * 24
+ + Func(Value("hour"), now - OuterRef("created_at"), function="DATE_PART") * 60
+ ) + Func(Value("minute"), now - OuterRef("created_at"), function="DATE_PART")
+
+ channels = Channel.objects.filter(
+ id=OuterRef("channel"),
+ expire_orders_after__isnull=False,
+ expire_orders_after__gt=0,
+ expire_orders_after__lte=time_diff_func_in_minutes,
+ )
+
+ qs = Order.objects.filter(
+ ~Exists(TransactionItem.objects.filter(order=OuterRef("pk"))),
+ ~Exists(Payment.objects.filter(order=OuterRef("pk"))),
+ Exists(channels),
+ status=OrderStatus.UNCONFIRMED,
+ )
+ for ids_batch in _queryset_in_batches(qs):
+ with traced_atomic_transaction():
+ Order.objects.filter(id__in=ids_batch).update(status=OrderStatus.EXPIRED)
+
+ _bulk_release_voucher_usage(ids_batch)
+ _order_expired_events(ids_batch)
+ deallocate_stock_for_orders(ids_batch, manager)
+ _call_expired_order_events(ids_batch, manager)
+
+
[email protected](soft_time_limit=60 * 30)
+def expire_orders_task():
+ now = timezone.now()
+ task_name = "expire_orders"
+ manager = get_plugins_manager()
+ try:
+ with celery_task_lock(task_name) as (lock_obj, acquired):
+ if not acquired:
+ if lock_obj.created_at < now - timedelta(hours=1):
+ logger.error("%s task exceeded 1h working time.", [task_name])
+ else:
+ _expire_orders(manager, now)
+
+ except SoftTimeLimitExceeded as e:
+ logger.error(e)
diff --git a/saleor/order/tests/test_tasks.py b/saleor/order/tests/test_tasks.py
new file mode 100644
index 0000000000..1403519434
--- /dev/null
+++ b/saleor/order/tests/test_tasks.py
@@ -0,0 +1,382 @@
+from unittest.mock import patch
+
+import pytest
+from django.utils import timezone
+
+from ...core.models import CeleryTask
+from ...discount.models import VoucherCustomer
+from ...warehouse.models import Allocation
+from .. import OrderEvents, OrderStatus
+from ..models import OrderEvent
+from ..tasks import expire_orders_task
+
+
+def test_expire_orders_task_check_voucher(
+ order_list, allocations, channel_USD, voucher_customer
+):
+ # given
+ channel_USD.expire_orders_after = 1
+ channel_USD.save()
+
+ now = timezone.now()
+ voucher = voucher_customer.voucher
+ voucher.used = 3
+ voucher.usage_limit = 3
+ voucher.save()
+
+ order_1 = order_list[0]
+ order_1.status = OrderStatus.UNCONFIRMED
+ order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.voucher = voucher
+ order_1.save()
+
+ order_2 = order_list[1]
+ order_2.status = OrderStatus.UNCONFIRMED
+ order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.voucher = voucher
+ order_2.save()
+
+ order_3 = order_list[2]
+ order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.status = OrderStatus.UNFULFILLED
+ order_3.voucher = voucher
+ order_3.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ for order in order_list:
+ order.refresh_from_db()
+ assert order_1.status == OrderStatus.EXPIRED
+ assert order_2.status == OrderStatus.EXPIRED
+ assert order_3.status == OrderStatus.UNFULFILLED
+
+ assert not Allocation.objects.filter(
+ order_line__order=order_1, quantity_allocated__gt=0
+ ).exists()
+ assert not Allocation.objects.filter(
+ order_line__order=order_2, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_3, quantity_allocated__gt=0
+ ).exists()
+
+ voucher.refresh_from_db()
+ assert voucher.used == 1
+ assert not VoucherCustomer.objects.filter(pk=voucher_customer.pk).exists()
+
+
+def test_expire_orders_task_check_multiple_vouchers(
+ order_list,
+ allocations,
+ channel_USD,
+ voucher,
+ voucher_percentage,
+):
+ # given
+ channel_USD.expire_orders_after = 1
+ channel_USD.save()
+
+ now = timezone.now()
+ voucher.used = 2
+ voucher.usage_limit = 2
+ voucher.save()
+ voucher_percentage.used = 1
+ voucher_percentage.usage_limit = 1
+ voucher_percentage.save()
+
+ order_1 = order_list[0]
+ order_1.status = OrderStatus.UNCONFIRMED
+ order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.voucher = voucher
+ order_1.save()
+
+ order_2 = order_list[1]
+ order_2.status = OrderStatus.UNCONFIRMED
+ order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.voucher = voucher_percentage
+ order_2.save()
+
+ order_3 = order_list[2]
+ order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.status = OrderStatus.UNFULFILLED
+ order_3.voucher = voucher
+ order_3.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ for order in order_list:
+ order.refresh_from_db()
+ assert order_1.status == OrderStatus.EXPIRED
+ assert order_2.status == OrderStatus.EXPIRED
+ assert order_3.status == OrderStatus.UNFULFILLED
+
+ assert not Allocation.objects.filter(
+ order_line__order=order_1, quantity_allocated__gt=0
+ ).exists()
+ assert not Allocation.objects.filter(
+ order_line__order=order_2, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_3, quantity_allocated__gt=0
+ ).exists()
+
+ voucher.refresh_from_db()
+ assert voucher.used == 1
+ voucher_percentage.refresh_from_db()
+ assert voucher_percentage.used == 0
+
+
+def test_expire_orders_task_creates_order_events(order_list, allocations, channel_USD):
+ # given
+ channel_USD.expire_orders_after = 60
+ channel_USD.save()
+
+ now = timezone.now()
+ order_1 = order_list[0]
+ order_1.created_at = now
+ order_1.status = OrderStatus.UNCONFIRMED
+ order_1.save()
+
+ order_2 = order_list[1]
+ order_2.created_at = now - timezone.timedelta(minutes=120)
+ order_2.status = OrderStatus.UNCONFIRMED
+ order_2.save()
+
+ order_3 = order_list[2]
+ order_3.created_at = now - timezone.timedelta(minutes=120)
+ order_3.status = OrderStatus.UNFULFILLED
+ order_3.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ for order in order_list:
+ order.refresh_from_db()
+ assert order_1.status == OrderStatus.UNCONFIRMED
+ assert order_2.status == OrderStatus.EXPIRED
+ assert order_3.status == OrderStatus.UNFULFILLED
+
+ assert not OrderEvent.objects.filter(
+ order_id=order_1.pk,
+ type=OrderEvents.EXPIRED,
+ ).exists()
+ assert OrderEvent.objects.filter(
+ order_id=order_2.pk,
+ type=OrderEvents.EXPIRED,
+ ).exists()
+ assert not OrderEvent.objects.filter(
+ order_id=order_3.pk,
+ type=OrderEvents.EXPIRED,
+ ).exists()
+
+
+def test_expire_orders_task_with_transaction_item(
+ order_list,
+ transaction_item,
+ allocations,
+ channel_USD,
+):
+ # given
+ channel_USD.expire_orders_after = 1
+ channel_USD.save()
+
+ now = timezone.now()
+
+ order_1 = order_list[0]
+ order_1.status = OrderStatus.UNCONFIRMED
+ order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.save()
+
+ order_2 = order_list[1]
+ order_2.status = OrderStatus.UNCONFIRMED
+ order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.save()
+
+ order_3 = order_list[2]
+ order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.status = OrderStatus.UNFULFILLED
+ order_3.save()
+
+ transaction_item.order_id = order_2.pk
+ transaction_item.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ for order in order_list:
+ order.refresh_from_db()
+ assert order_1.status == OrderStatus.EXPIRED
+ assert order_2.status == OrderStatus.UNCONFIRMED
+ assert order_3.status == OrderStatus.UNFULFILLED
+
+ assert not Allocation.objects.filter(
+ order_line__order=order_1, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_2, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_3, quantity_allocated__gt=0
+ ).exists()
+
+
+def test_expire_orders_task_with_payment(
+ order_list,
+ payment_dummy,
+ allocations,
+ channel_USD,
+):
+ # given
+ channel_USD.expire_orders_after = 1
+ channel_USD.save()
+
+ now = timezone.now()
+
+ order_1 = order_list[0]
+ order_1.status = OrderStatus.UNCONFIRMED
+ order_1.created_at = now - timezone.timedelta(minutes=10)
+ order_1.save()
+
+ order_2 = order_list[1]
+ order_2.status = OrderStatus.UNCONFIRMED
+ order_2.created_at = now - timezone.timedelta(minutes=10)
+ order_2.save()
+
+ order_3 = order_list[2]
+ order_3.created_at = now - timezone.timedelta(minutes=10)
+ order_3.status = OrderStatus.UNFULFILLED
+ order_3.save()
+
+ payment_dummy.order_id = order_2.pk
+ payment_dummy.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ for order in order_list:
+ order.refresh_from_db()
+ assert order_1.status == OrderStatus.EXPIRED
+ assert order_2.status == OrderStatus.UNCONFIRMED
+ assert order_3.status == OrderStatus.UNFULFILLED
+
+ assert not Allocation.objects.filter(
+ order_line__order=order_1, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_2, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_3, quantity_allocated__gt=0
+ ).exists()
+
+
[email protected]("expire_after", [None, 0, -1])
+def test_expire_orders_task_none_expiration_time(
+ expire_after,
+ order_list,
+ allocations,
+ channel_USD,
+):
+ # given
+ channel_USD.expire_orders_after = expire_after
+ channel_USD.save()
+
+ order_1 = order_list[0]
+ order_1.status = OrderStatus.UNCONFIRMED
+ order_1.save()
+
+ order_2 = order_list[1]
+ order_2.status = OrderStatus.UNCONFIRMED
+ order_2.save()
+
+ order_3 = order_list[2]
+ order_3.status = OrderStatus.UNFULFILLED
+ order_3.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ for order in order_list:
+ order.refresh_from_db()
+ assert order_1.status == OrderStatus.UNCONFIRMED
+ assert order_2.status == OrderStatus.UNCONFIRMED
+ assert order_3.status == OrderStatus.UNFULFILLED
+
+ assert Allocation.objects.filter(
+ order_line__order=order_1, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_2, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_3, quantity_allocated__gt=0
+ ).exists()
+
+
+def test_expire_orders_task_after(order_list, allocations, channel_USD):
+ # given
+ channel_USD.expire_orders_after = 60
+ channel_USD.save()
+
+ now = timezone.now()
+ order_1 = order_list[0]
+ order_1.created_at = now
+ order_1.status = OrderStatus.UNCONFIRMED
+ order_1.save()
+
+ order_2 = order_list[1]
+ order_2.created_at = now - timezone.timedelta(minutes=120)
+ order_2.status = OrderStatus.UNCONFIRMED
+ order_2.save()
+
+ order_3 = order_list[2]
+ order_3.created_at = now - timezone.timedelta(minutes=120)
+ order_3.status = OrderStatus.UNFULFILLED
+ order_3.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ for order in order_list:
+ order.refresh_from_db()
+ assert order_1.status == OrderStatus.UNCONFIRMED
+ assert order_2.status == OrderStatus.EXPIRED
+ assert order_3.status == OrderStatus.UNFULFILLED
+
+ assert Allocation.objects.filter(
+ order_line__order=order_1, quantity_allocated__gt=0
+ ).exists()
+ assert not Allocation.objects.filter(
+ order_line__order=order_2, quantity_allocated__gt=0
+ ).exists()
+ assert Allocation.objects.filter(
+ order_line__order=order_3, quantity_allocated__gt=0
+ ).exists()
+
+
+@patch("logging.Logger.error")
+def test_expire_orders_task_locked_over_hour(logger_mock, order_list, allocations):
+ # given
+ task_name = "expire_orders"
+ error_msg = "%s task exceeded 1h working time."
+
+ now = timezone.now()
+
+ lock = CeleryTask.objects.create(name=task_name)
+ lock.created_at = now - timezone.timedelta(hours=2)
+ lock.save()
+
+ # when
+ expire_orders_task()
+
+ # then
+ logger_mock.assert_called_once_with(error_msg, [task_name])
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index baae094f04..fad6a0a829 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -669,6 +669,12 @@ class BasePlugin:
# canceled.
order_cancelled: Callable[["Order", Any], Any]
+ # Trigger when order is expired.
+ #
+ # Overwrite this method if you need to trigger specific logic when an order is
+ # expired.
+ order_expired: Callable[["Order", Any], Any]
+
# Trigger when order is confirmed by staff.
#
# Overwrite this method if you need to trigger specific logic after an order is
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 8e03123f75..d23c26f17a 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -826,6 +826,12 @@ class PluginsManager(PaymentInterface):
"order_cancelled", default_value, order, channel_slug=order.channel.slug
)
+ def order_expired(self, order: "Order"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "order_expired", default_value, order, channel_slug=order.channel.slug
+ )
+
def order_fulfilled(self, order: "Order"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 7dfeebdbea..502ee77121 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -502,6 +502,16 @@ class WebhookPlugin(BasePlugin):
order_data, event_type, webhooks, order, self.requestor
)
+ def order_expired(self, order: "Order", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.ORDER_EXPIRED
+ if webhooks := get_webhooks_for_event(event_type):
+ order_data = generate_order_payload(order, self.requestor)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
+
def sale_created(
self,
sale: "Sale",
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index dd3aa8f32a..30a2985154 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -436,6 +436,13 @@ def subscription_order_cancelled_webhook(subscription_webhook):
)
+def subscription_order_expired_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.ORDER_EXPIRED, WebhookEventAsyncType.ORDER_EXPIRED
+ )
+
+
@pytest.fixture
def subscription_order_fulfilled_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
index 8663bf0d9b..0070c15fb7 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -878,6 +878,20 @@ ORDER_CANCELLED = """
}
"""
+
+ORDER_EXPIRED = """
+ subscription{
+ event{
+ ...on OrderExpired{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
ORDER_FULFILLED = """
subscription{
event{
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 029aff950c..5242c315ea 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
@@ -1191,6 +1191,22 @@ def test_order_cancelled(order, subscription_order_cancelled_webhook):
assert deliveries[0].webhook == webhooks[0]
+def test_order_expired(order, subscription_order_expired_webhook):
+ # given
+ webhooks = [subscription_order_expired_webhook]
+ event_type = WebhookEventAsyncType.ORDER_EXPIRED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ expected_payload = json.dumps({"order": {"id": order_id}})
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+
+ # then
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_order_fulfilled(order, subscription_order_fulfilled_webhook):
webhooks = [subscription_order_fulfilled_webhook]
event_type = WebhookEventAsyncType.ORDER_FULFILLED
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 036615e20f..18f842f518 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -765,6 +765,31 @@ def test_order_cancelled(
)
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_order_expired(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order_with_lines,
+):
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ manager.order_expired(order_with_lines)
+ expected_data = generate_order_payload(order_with_lines)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data,
+ WebhookEventAsyncType.ORDER_EXPIRED,
+ [any_webhook],
+ order_with_lines,
+ None,
+ )
+
+
@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/settings.py b/saleor/settings.py
index da97f3a867..041539a264 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -549,6 +549,11 @@ CELERY_TASK_ROUTES = {
},
}
+# Expire orders task setting
+BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA = timedelta(
+ seconds=parse(os.environ.get("BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA", "5 minutes"))
+)
+
# Defines after how many seconds should the task triggered by the Celery beat
# entry 'update-products-search-vectors' expire if it wasn't picked up by a worker.
BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC = 20
@@ -601,6 +606,10 @@ CELERY_BEAT_SCHEDULE = {
"schedule": timedelta(seconds=20),
"options": {"expires": BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC},
},
+ "expire-orders": {
+ "task": "saleor.order.tasks.expire_orders_task",
+ "schedule": BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA,
+ },
}
# The maximum wait time between each is_due() call on schedulers
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 629e7111e9..67c476892e 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -316,6 +316,20 @@ def checkout_with_item(checkout, product):
return checkout
+def checkout_with_item_and_transaction_item(checkout_with_item):
+ TransactionItem.objects.create(
+ status="Captured",
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=["refund"],
+ currency="USD",
+ checkout_id=checkout_with_item.pk,
+ charged_value=Decimal("10"),
+ )
+ return checkout_with_item
+
+
@pytest.fixture
def checkout_with_item_and_tax_exemption(checkout_with_item):
checkout_with_item.tax_exemption = True
@@ -4568,6 +4582,14 @@ def fulfilled_order(order_with_lines):
return order
+def unconfirmed_order_with_lines(order_with_lines):
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+ return order
+
+
@pytest.fixture
def fulfilled_order_without_inventory_tracking(
order_with_line_without_inventory_tracking,
@@ -5616,6 +5638,13 @@ def transaction_item_created_by_user(order, staff_user, transaction_item_generat
)
+def transaction_item(order, transaction_item_generator):
+ return transaction_item_generator(
+ order_id=order.pk,
+ )
+
+
@pytest.fixture
def digital_content(category, media_root, warehouse, channel_USD) -> DigitalContent:
product_type = ProductType.objects.create(
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index dbad12d11e..dfa4980a74 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -612,6 +612,30 @@ def deallocate_stock_for_order(order: "Order", manager: PluginsManager):
Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
+@traced_atomic_transaction()
+def deallocate_stock_for_orders(orders_id, manager: PluginsManager):
+ """Remove all allocations for given order."""
+ lines = OrderLine.objects.filter(order_id__in=orders_id)
+ allocations = Allocation.objects.filter(
+ Exists(lines.filter(id=OuterRef("order_line_id"))), quantity_allocated__gt=0
+ ).select_related("stock")
+
+ stocks_to_update = []
+ for alloc in allocations:
+ stock = alloc.stock
+ stock.quantity_allocated = F("quantity_allocated") - alloc.quantity_allocated
+ stocks_to_update.append(stock)
+
+ for allocation in allocations.annotate_stock_available_quantity():
+ if allocation.stock_available_quantity <= 0:
+ transaction.on_commit(
+ lambda: manager.product_variant_back_in_stock(allocation.stock)
+ )
+
+ allocations.update(quantity_allocated=0)
+ Stock.objects.bulk_update(stocks_to_update, ["quantity_allocated"])
+
+
@traced_atomic_transaction()
def allocate_preorders(
order_lines_info: Iterable["OrderLineInfo"],
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 07984c39f6..bd0c6b0f19 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -63,6 +63,7 @@ class WebhookEventAsyncType:
ORDER_FULLY_PAID = "order_fully_paid"
ORDER_UPDATED = "order_updated"
ORDER_CANCELLED = "order_cancelled"
+ ORDER_EXPIRED = "order_expired"
ORDER_FULFILLED = "order_fulfilled"
ORDER_METADATA_UPDATED = "order_metadata_updated"
@@ -202,6 +203,7 @@ class WebhookEventAsyncType:
ORDER_FULLY_PAID: "Order paid",
ORDER_UPDATED: "Order updated",
ORDER_CANCELLED: "Order cancelled",
+ ORDER_EXPIRED: "Order expired",
ORDER_FULFILLED: "Order fulfilled",
ORDER_METADATA_UPDATED: "Order metadata updated",
DRAFT_ORDER_CREATED: "Draft order created",
@@ -318,6 +320,7 @@ class WebhookEventAsyncType:
(ORDER_FULLY_PAID, DISPLAY_LABELS[ORDER_FULLY_PAID]),
(ORDER_UPDATED, DISPLAY_LABELS[ORDER_UPDATED]),
(ORDER_CANCELLED, DISPLAY_LABELS[ORDER_CANCELLED]),
+ (ORDER_EXPIRED, DISPLAY_LABELS[ORDER_EXPIRED]),
(ORDER_FULFILLED, DISPLAY_LABELS[ORDER_FULFILLED]),
(ORDER_METADATA_UPDATED, DISPLAY_LABELS[ORDER_METADATA_UPDATED]),
(DRAFT_ORDER_CREATED, DISPLAY_LABELS[DRAFT_ORDER_CREATED]),
@@ -444,6 +447,7 @@ class WebhookEventAsyncType:
ORDER_FULLY_PAID: OrderPermissions.MANAGE_ORDERS,
ORDER_UPDATED: OrderPermissions.MANAGE_ORDERS,
ORDER_CANCELLED: OrderPermissions.MANAGE_ORDERS,
+ ORDER_EXPIRED: OrderPermissions.MANAGE_ORDERS,
ORDER_FULFILLED: OrderPermissions.MANAGE_ORDERS,
ORDER_METADATA_UPDATED: OrderPermissions.MANAGE_ORDERS,
DRAFT_ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 5f539e9eb0..b8cebf24a1 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -1106,6 +1106,7 @@ def _generate_sample_order_payload(event_name):
elif event_name in [
WebhookEventAsyncType.ORDER_CANCELLED,
WebhookEventAsyncType.ORDER_UPDATED,
+ WebhookEventAsyncType.ORDER_EXPIRED,
]:
order = _get_sample_object(order_qs.filter(status=OrderStatus.CANCELED))
if order:
diff --git a/saleor/webhook/tests/test_webhook_sample_payloads.py b/saleor/webhook/tests/test_webhook_sample_payloads.py
index a2e4a32633..c010eb5c29 100644
--- a/saleor/webhook/tests/test_webhook_sample_payloads.py
+++ b/saleor/webhook/tests/test_webhook_sample_payloads.py
@@ -36,6 +36,7 @@ def _remove_anonymized_order_data(order_data: dict) -> dict:
(WebhookEventAsyncType.ORDER_CREATED, OrderStatus.UNFULFILLED),
(WebhookEventAsyncType.ORDER_UPDATED, OrderStatus.CANCELED),
(WebhookEventAsyncType.ORDER_CANCELLED, OrderStatus.CANCELED),
+ (WebhookEventAsyncType.ORDER_EXPIRED, OrderStatus.CANCELED),
(WebhookEventAsyncType.ORDER_FULFILLED, OrderStatus.FULFILLED),
(WebhookEventAsyncType.ORDER_FULLY_PAID, OrderStatus.FULFILLED),
],