Skip to content

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

New event for starting and ending sales (#10110)

Iga Karbowiak67492396aa41
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb5fd5587f..f3e4381a60 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Added `metadata` fields to `OrderLine` and `CheckoutLine` models - #10040 by @SzymJ
- Improve checkout total base calculations - #10048 by @IKarbowiak
- Improve click & collect and stock allocation - #10043 by @IKarbowiak
+- New event for starting and ending sales - #10110 by @IKarbowiak
#### Saleor Apps
- Add webhooks `PAGE_TYPE_CREATED`, `PAGE_TYPE_UPDATED` and `PAGE_TYPE_DELETED` - #9859 by @SzymJ
diff --git a/saleor/core/schedules.py b/saleor/core/schedules.py
new file mode 100644
index 0000000000..34e892419d
--- /dev/null
+++ b/saleor/core/schedules.py
@@ -0,0 +1,103 @@
+from collections import namedtuple
+from datetime import datetime
+
+import pytz
+from celery.schedules import BaseSchedule
+from celery.utils.time import maybe_timedelta, remaining
+from django.db.models import F, Q
+
+schedstate = namedtuple("schedstate", ("is_due", "next"))
+
+
+class sale_webhook_schedule(BaseSchedule):
+ """Schedule for sale webhook periodic task.
+
+ The lowercase with an underscore is used for the name as all celery schedules
+ are written this way. According to PEP it's allowed behavior:
+ https://peps.python.org/pep-0008/#class-names.
+
+ Arguments:
+ initial_timedelta (float, ~datetime.timedelta):
+ Initial time interval in seconds.
+ nowfun (Callable): Function returning the current date and time
+ (:class:`~datetime.datetime`).
+ app (Celery): Celery app instance.
+
+ """
+
+ def __init__(self, initial_timedelta=60, nowfun=None, app=None):
+ self.initial_timedelta = maybe_timedelta(initial_timedelta)
+ self.next_run = self.initial_timedelta
+ super().__init__(nowfun=nowfun, app=app)
+
+ def remaining_estimate(self, last_run_at):
+ """Estimate of next run time.
+
+ Returns when the periodic task should run next as a timedelta.
+ """
+ return remaining(
+ self.maybe_make_aware(last_run_at),
+ self.next_run,
+ self.maybe_make_aware(self.now()),
+ )
+
+ def is_due(self, last_run_at):
+ """Return tuple of ``(is_due, next_time_to_run)``.
+
+ Note:
+ Next time to run is in seconds.
+
+ """
+ from ..discount.models import Sale
+ from ..discount.tasks import get_sales_to_notify_about
+
+ now = datetime.now(pytz.UTC)
+
+ # remaining time must be calculated as the next call is overridden with 0
+ # when is_due was True (/celery/beat.py Scheduler.populate_heap)
+ rem_delta = self.remaining_estimate(last_run_at)
+ remaining = max(rem_delta.total_seconds(), 0)
+
+ # is_due is True when there is at least one sale to notify about
+ # and the remaining time from previous call is 0
+ is_due = remaining == 0 and get_sales_to_notify_about().exists()
+
+ upcoming_start_dates = Sale.objects.filter(
+ (
+ (
+ Q(notification_sent_datetime__isnull=True)
+ | Q(notification_sent_datetime__lt=F("start_date"))
+ )
+ & Q(start_date__gt=now)
+ )
+ ).order_by("start_date")
+ upcoming_end_dates = Sale.objects.filter(
+ (
+ (
+ Q(notification_sent_datetime__isnull=True)
+ | Q(notification_sent_datetime__lt=F("end_date"))
+ )
+ & Q(end_date__gt=now)
+ )
+ ).order_by("end_date")
+
+ if not upcoming_start_dates and not upcoming_end_dates:
+ self.next_run = self.initial_timedelta
+ return schedstate(is_due, self.next_run.total_seconds())
+
+ # calculate the earliest incoming date of starting or ending sale
+ next_start_date = (
+ upcoming_start_dates.first().start_date if upcoming_start_dates else None
+ )
+ next_end_date = (
+ upcoming_end_dates.first().end_date if upcoming_end_dates else None
+ )
+
+ # get the earlier date
+ if next_start_date and next_end_date:
+ next_upcoming_date = min(next_start_date, next_end_date)
+ else:
+ next_upcoming_date = next_start_date if next_start_date else next_end_date
+
+ self.next_run = min((next_upcoming_date - now), self.initial_timedelta)
+ return schedstate(is_due, self.next_run.total_seconds())
diff --git a/saleor/core/tests/test_schedules.py b/saleor/core/tests/test_schedules.py
new file mode 100644
index 0000000000..be1ee52579
--- /dev/null
+++ b/saleor/core/tests/test_schedules.py
@@ -0,0 +1,193 @@
+from datetime import timedelta
+
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ...discount.models import Sale
+from ..schedules import sale_webhook_schedule
+
+
+@freeze_time("2020-10-10 12:00:00")
+def test_sale_webhook_schedule_remaining_estimate_initial_state():
+ # given
+ schedule = sale_webhook_schedule()
+
+ # when
+ remaining = schedule.remaining_estimate(last_run_at=timezone.now())
+
+ # then
+ assert remaining == schedule.initial_timedelta
+
+
+@freeze_time("2020-10-10 12:00:00")
+def test_sale_webhook_schedule_remaining_estimate():
+ # given
+ schedule = sale_webhook_schedule()
+ time_delta = timedelta(seconds=30)
+
+ # when
+ remaining = schedule.remaining_estimate(last_run_at=timezone.now() - time_delta)
+
+ # then
+ assert remaining == schedule.initial_timedelta - time_delta
+
+
+def test_is_due_not_sale_to_notify_about_not_upcoming_sale(sale, new_sale):
+ # given
+ now = timezone.now()
+ schedule = sale_webhook_schedule()
+ sale.start_date = now - timedelta(days=1)
+ sale.notification_sent_datetime = now - timedelta(minutes=2)
+
+ new_sale.start_date = now - timedelta(days=2)
+ new_sale.notification_sent_datetime = now - timedelta(minutes=2)
+
+ Sale.objects.bulk_update(
+ [sale, new_sale], ["start_date", "notification_sent_datetime"]
+ )
+
+ # when
+ is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+
+ # then
+ assert is_due is False
+ assert next_run == schedule.initial_timedelta.total_seconds()
+
+
+def test_is_due_sale_started_to_notify_and_not_upcoming_sale(sale, new_sale):
+ # given
+ now = timezone.now()
+ schedule = sale_webhook_schedule()
+ sale.start_date = now - timedelta(minutes=5)
+ sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ new_sale.start_date = now - timedelta(days=2)
+ new_sale.notification_sent_datetime = now - timedelta(minutes=2)
+
+ Sale.objects.bulk_update(
+ [sale, new_sale],
+ ["start_date", "notification_sent_datetime"],
+ )
+
+ # when
+ is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+
+ # then
+ assert is_due is True
+ assert next_run == schedule.initial_timedelta.total_seconds()
+
+
+def test_is_due_sale_ended_to_notify_and_not_upcoming_sale(sale, new_sale):
+ # given
+ now = timezone.now()
+ schedule = sale_webhook_schedule()
+
+ sale.start_date = now - timedelta(days=2)
+ sale.notification_sent_datetime = now - timedelta(minutes=2)
+
+ new_sale.start_date = now - timedelta(days=1)
+ new_sale.end_date = now - timedelta(minutes=5)
+ new_sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ Sale.objects.bulk_update(
+ [sale, new_sale],
+ [
+ "start_date",
+ "end_date",
+ "notification_sent_datetime",
+ ],
+ )
+
+ # when
+ is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+
+ # then
+ assert is_due is True
+ assert next_run == schedule.initial_timedelta.total_seconds()
+
+
+@freeze_time("2020-10-10 12:00:00")
+def test_is_due_sale_started_to_notify_and_upcoming_sale(sale, new_sale):
+ # given
+ now = timezone.now()
+ schedule = sale_webhook_schedule()
+
+ sale.start_date = now - timedelta(minutes=5)
+ sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ time_delta = timedelta(seconds=44)
+ new_sale.start_date = now - timedelta(minutes=7)
+ new_sale.end_date = timezone.now() + time_delta
+ new_sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ Sale.objects.bulk_update(
+ [sale, new_sale],
+ [
+ "start_date",
+ "end_date",
+ "notification_sent_datetime",
+ ],
+ )
+
+ # when
+ is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+
+ # then
+ assert is_due is True
+ assert next_run == time_delta.total_seconds()
+
+
+@freeze_time("2020-10-10 12:00:00")
+def test_is_due_no_sale_to_notify_about_and_upcoming_sale_exists(sale, new_sale):
+ # given
+ now = timezone.now()
+ schedule = sale_webhook_schedule()
+
+ sale.start_date = now - timedelta(minutes=8)
+ sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ time_delta = timedelta(seconds=22)
+ new_sale.start_date = now - timedelta(minutes=7)
+ new_sale.end_date = timezone.now() + time_delta
+ new_sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ Sale.objects.bulk_update(
+ [sale, new_sale],
+ ["start_date", "end_date", "notification_sent_datetime"],
+ )
+
+ # when
+ is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+
+ # then
+ assert is_due is False
+ assert next_run == time_delta.total_seconds()
+
+
+@freeze_time("2020-10-10 12:00:00")
+def test_is_due_no_sale_to_notify_about_and_upcoming_sale_exists_initial_time_returned(
+ sale, new_sale
+):
+ # given
+ now = timezone.now()
+ schedule = sale_webhook_schedule()
+
+ sale.start_date = now - timedelta(minutes=8)
+ sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ time_delta = timedelta(minutes=3)
+ new_sale.start_date = now - timedelta(minutes=7)
+ new_sale.end_date = timezone.now() + time_delta
+ new_sale.notification_sent_datetime = now - timedelta(minutes=6)
+
+ Sale.objects.bulk_update(
+ [sale, new_sale],
+ ["end_date", "notification_sent_datetime"],
+ )
+
+ # when
+ is_due, next_run = schedule.is_due(timezone.now() - timedelta(minutes=1))
+
+ # then
+ assert is_due is False
+ assert next_run == schedule.initial_timedelta.total_seconds()
diff --git a/saleor/discount/migrations/0043_sale_notification_sent_datetime.py b/saleor/discount/migrations/0043_sale_notification_sent_datetime.py
new file mode 100644
index 0000000000..4c31e782ec
--- /dev/null
+++ b/saleor/discount/migrations/0043_sale_notification_sent_datetime.py
@@ -0,0 +1,26 @@
+# Generated by Django 3.2.13 on 2022-07-08 06:41
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0042_migrate_orderdiscount_id_to_uuid"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sale",
+ name="notification_sent_datetime",
+ # The notification date is set to the current date, as the Celery would
+ # trigger the tasks right after the deployment and we would send
+ # events that no one listens to. So we will receive the same result with
+ # setting the current date and not sending the events at first place.
+ field=models.DateTimeField(
+ null=True, blank=True, default=django.utils.timezone.now
+ ),
+ preserve_default=False,
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 8c15b57f69..7d0c219032 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -1,8 +1,10 @@
+from datetime import datetime
from decimal import Decimal
from functools import partial
from typing import TYPE_CHECKING, Optional
from uuid import uuid4
+import pytz
from django.conf import settings
from django.contrib.postgres.indexes import GinIndex
from django.db import models
@@ -268,6 +270,8 @@ class Sale(ModelWithMetadata):
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
updated_at = models.DateTimeField(auto_now=True, db_index=True)
+ notification_sent_datetime = models.DateTimeField(null=True, blank=True)
+
objects = models.Manager.from_queryset(SaleQueryset)()
translated = TranslationProxy()
@@ -305,6 +309,11 @@ class Sale(ModelWithMetadata):
)
raise NotImplementedError("Unknown discount type")
+ def is_active(self, date=None):
+ if date is None:
+ date = datetime.now(pytz.utc)
+ return (not self.end_date or self.end_date >= date) and self.start_date <= date
+
class SaleChannelListing(models.Model):
sale = models.ForeignKey(
diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.py
new file mode 100644
index 0000000000..ec1414e3ca
--- /dev/null
+++ b/saleor/discount/tasks.py
@@ -0,0 +1,76 @@
+from collections import defaultdict
+from datetime import datetime
+
+import pytz
+from celery.utils.log import get_task_logger
+from django.db.models import F, Q
+
+from ..celeryconf import app
+from ..plugins.manager import get_plugins_manager
+from .models import Sale
+from .utils import CATALOGUE_FIELDS, CatalogueInfo
+
+task_logger = get_task_logger(__name__)
+
+
+def send_sale_toggle_notifications():
+ """Send the notification about starting or ending sales."""
+ manager = get_plugins_manager()
+
+ sales = get_sales_to_notify_about()
+
+ catalogue_infos = fetch_catalogue_infos(sales)
+
+ if not sales:
+ return
+
+ for sale in sales:
+ catalogues = catalogue_infos.get(sale.id)
+ manager.sale_toggle(sale, catalogues)
+
+ sale_ids = ", ".join([str(sale.id) for sale in sales])
+ sales.update(notification_sent_datetime=datetime.now(pytz.UTC))
+
+ task_logger.info("The sale_toggle webhook sent for sales with ids: %s", sale_ids)
+
+
+def fetch_catalogue_infos(sales):
+ catalogue_info: CatalogueInfo = {}
+ for sale_data in sales.values("id", *CATALOGUE_FIELDS):
+ sale_id = sale_data["id"]
+ if sale_id not in catalogue_info:
+ catalogue_info[sale_data["id"]] = defaultdict(set)
+
+ for field in CATALOGUE_FIELDS:
+ if id := sale_data.get(field):
+ catalogue_info[sale_data["id"]][field].add(id)
+
+ return catalogue_info
+
+
+def get_sales_to_notify_about():
+ """Return sales for which the notify should be sent.
+
+ The notification should be sent for sales for which the start date or end date
+ has passed and the notification date is null or the last notification was sent
+ before the start or end date.
+ """
+ now = datetime.now(pytz.UTC)
+ sales = Sale.objects.filter(
+ (
+ (
+ Q(notification_sent_datetime__isnull=True)
+ | Q(notification_sent_datetime__lt=F("start_date"))
+ )
+ & Q(start_date__lte=now)
+ )
+ | (
+ (
+ Q(notification_sent_datetime__isnull=True)
+ | Q(notification_sent_datetime__lt=F("end_date"))
+ )
+ & Q(end_date__lte=now)
+ )
+ ).distinct()
+ return sales
diff --git a/saleor/discount/tests/test_tasks.py b/saleor/discount/tests/test_tasks.py
new file mode 100644
index 0000000000..ad51d0df67
--- /dev/null
+++ b/saleor/discount/tests/test_tasks.py
@@ -0,0 +1,113 @@
+from datetime import timedelta
+from unittest.mock import ANY, patch
+
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ..models import Sale
+from ..tasks import fetch_catalogue_infos, send_sale_toggle_notifications
+
+
+def test_fetch_catalogue_infos(sale, new_sale):
+ # given
+ sales = Sale.objects.all()
+
+ # when
+ catalogue_infos = fetch_catalogue_infos(sales)
+
+ # then
+ for sale_instance in sales:
+ catalogue_info = catalogue_infos[sale_instance.id]
+ assert catalogue_info["categories"] == set(
+ sale_instance.categories.all().values_list("id", flat=True)
+ )
+ assert catalogue_info["collections"] == set(
+ sale_instance.collections.all().values_list("id", flat=True)
+ )
+ assert catalogue_info["products"] == set(
+ sale_instance.products.all().values_list("id", flat=True)
+ )
+ assert catalogue_info["variants"] == set(
+ sale_instance.variants.all().values_list("id", flat=True)
+ )
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+def test_send_sale_toggle_notifications(sale_toggle_mock):
+ # given
+ now = timezone.now()
+ sales = Sale.objects.bulk_create([Sale(name=f"Sale-{i}") for i in range(10)])
+
+ # sales with start date before current date
+ # without notification sent day - should be sent
+ sales[0].start_date = now - timedelta(days=1)
+ sales[0].notification_sent_datetime = None
+
+ # with notification sent day after the start date - shouldn't be sent
+ sales[1].start_date = now - timedelta(days=1)
+ sales[1].notification_sent_datetime = now - timedelta(minutes=2)
+
+ # with notification sent day before the start date - should be sent
+ sales[2].start_date = now - timedelta(minutes=2)
+ sales[2].notification_sent_datetime = now - timedelta(minutes=5)
+
+ # sales with start date after current date - shouldn't be sent
+ # without notification sent day
+ sales[3].start_date = now + timedelta(days=1)
+ sales[3].notification_sent_datetime = None
+
+ # with notification sent day before the start date
+ sales[4].start_date = now + timedelta(days=1)
+ sales[4].notification_sent_datetime = now - timedelta(minutes=5)
+
+ # sales with end date before current date
+ # without notification sent day - should be sent
+ sales[5].end_date = now - timedelta(days=1)
+ sales[5].notification_sent_datetime = None
+
+ # with notification sent day after the start date - shouldn't be sent
+ sales[6].start_date = now - timedelta(days=2)
+ sales[6].end_date = now - timedelta(days=1)
+ sales[6].notification_sent_datetime = now - timedelta(minutes=2)
+
+ # with notification sent day before the start date - should be sent
+ sales[7].start_date = now - timedelta(days=2)
+ sales[7].end_date = now - timedelta(minutes=2)
+ sales[7].notification_sent_datetime = now - timedelta(minutes=5)
+
+ # sales with end date after current date
+ # without notification sent day
+ sales[8].start_date = now + timedelta(days=2)
+ sales[8].end_date = now + timedelta(days=1)
+ sales[8].notification_sent_datetime = None
+
+ # with notification sent day before the start date
+ sales[9].start_date = now + timedelta(days=2)
+ sales[9].end_date = now + timedelta(days=1)
+ sales[9].notification_sent_datetime = now - timedelta(minutes=5)
+
+ Sale.objects.bulk_update(
+ sales,
+ [
+ "start_date",
+ "end_date",
+ "notification_sent_datetime",
+ ],
+ )
+
+ # when
+ send_sale_toggle_notifications()
+
+ # then
+ assert sale_toggle_mock.call_count == 4
+
+ started_args_list = [args.args for args in sale_toggle_mock.call_args_list]
+ assert (sales[0], ANY) in started_args_list
+ assert (sales[2], ANY) in started_args_list
+ assert (sales[5], ANY) in started_args_list
+ assert (sales[7], ANY) in started_args_list
+
+ for index in [0, 2, 5, 7]:
+ sales[index].refresh_from_db()
+ assert sales[index].notification_sent_datetime == now
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index bd5a6650c6..51c2f6d266 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -33,6 +33,7 @@ if TYPE_CHECKING:
from .models import Voucher
CatalogueInfo = DefaultDict[str, Set[int]]
+CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]
def increase_voucher_usage(voucher: "Voucher") -> None:
@@ -351,12 +352,10 @@ def fetch_active_discounts() -> List[DiscountInfo]:
def fetch_catalogue_info(instance: Sale) -> CatalogueInfo:
- catalogue_fields = ["categories", "collections", "products", "variants"]
catalogue_info: CatalogueInfo = defaultdict(set)
-
- for field in catalogue_fields:
- catalogue_info[field].update(
- id_ for id_ in getattr(instance, field).all().values_list("id", flat=True)
- )
+ for sale_data in Sale.objects.filter(id=instance.id).values(*CATALOGUE_FIELDS):
+ for field in CATALOGUE_FIELDS:
+ if id := sale_data.get(field):
+ catalogue_info[field].add(id)
return catalogue_info
diff --git a/saleor/graphql/discount/mutations/sale_create.py b/saleor/graphql/discount/mutations/sale_create.py
index e6124ea3ae..ea06333b85 100644
--- a/saleor/graphql/discount/mutations/sale_create.py
+++ b/saleor/graphql/discount/mutations/sale_create.py
@@ -1,4 +1,7 @@
+from datetime import datetime
+
import graphene
+import pytz
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -90,12 +93,38 @@ class SaleCreate(SaleUpdateDiscountedPriceMixin, ModelMutation):
def perform_mutation(cls, _root, info, **data):
response = super().perform_mutation(_root, info, **data)
instance = getattr(response, cls._meta.return_field_name).node
- current_catalogue = fetch_catalogue_info(instance)
+ cls.send_sale_notifications(info, instance)
+ return response
+
+ @classmethod
+ def send_sale_notifications(cls, info, instance):
+ current_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(instance)
+ )
transaction.on_commit(
lambda: info.context.plugins.sale_created(
instance,
- convert_catalogue_info_to_global_ids(current_catalogue),
+ current_catalogue,
)
)
- return response
+
+ cls.send_sale_toggle_notification(info, instance, current_catalogue)
+
+ @staticmethod
+ def send_sale_toggle_notification(info, instance, catalogue):
+ """Send a notification about starting or ending sale if it hasn't been sent yet.
+
+ Send the notification when the start date is before the current date and the
+ sale is not already finished.
+ """
+ manager = info.context.plugins
+ now = datetime.now(pytz.utc)
+
+ start_date = instance.start_date
+ end_date = instance.end_date
+
+ if (start_date and start_date <= now) and (not end_date or not end_date <= now):
+ manager.sale_toggle(instance, catalogue)
+ instance.notification_sent_datetime = now
+ instance.save(update_fields=["notification_sent_datetime"])
diff --git a/saleor/graphql/discount/mutations/sale_update.py b/saleor/graphql/discount/mutations/sale_update.py
index 4d481d3085..bc54113efc 100644
--- a/saleor/graphql/discount/mutations/sale_update.py
+++ b/saleor/graphql/discount/mutations/sale_update.py
@@ -1,4 +1,7 @@
+from datetime import datetime
+
import graphene
+import pytz
from django.db import transaction
from ....core.permissions import DiscountPermissions
@@ -30,16 +33,74 @@ class SaleUpdate(SaleUpdateDiscountedPriceMixin, ModelMutation):
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
- node_id = data.get("id")
- instance = cls.get_node_or_error(info, node_id, only_type=Sale)
+ instance = cls.get_instance(info, **data)
previous_catalogue = fetch_catalogue_info(instance)
- response = super().perform_mutation(_root, info, **data)
- current_catalogue = fetch_catalogue_info(instance)
+ previous_end_date = instance.end_date
+ data = data.get("input")
+ cleaned_input = cls.clean_input(info, instance, data)
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+ cls.save(info, instance, cleaned_input)
+ cls._save_m2m(info, instance, cleaned_input)
+ cls.send_sale_notifications(
+ info, instance, cleaned_input, previous_catalogue, previous_end_date
+ )
+ return cls.success_response(instance)
+
+ @classmethod
+ def send_sale_notifications(
+ cls, info, instance, cleaned_input, previous_catalogue, previous_end_date
+ ):
+ current_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(instance)
+ )
transaction.on_commit(
lambda: info.context.plugins.sale_updated(
instance,
convert_catalogue_info_to_global_ids(previous_catalogue),
- convert_catalogue_info_to_global_ids(current_catalogue),
+ current_catalogue,
)
)
- return response
+
+ cls.send_sale_toggle_notification(
+ info, instance, cleaned_input, current_catalogue, previous_end_date
+ )
+
+ @staticmethod
+ def send_sale_toggle_notification(
+ info, instance, clean_input, catalogue, previous_end_date
+ ):
+ """Send the notification about starting or ending sale if it wasn't sent yet.
+
+ Send notification if the notification when the start or end date already passed
+ ans the notification_date is not set or the last notification was sent
+ before start or end date.
+ """
+ manager = info.context.plugins
+ now = datetime.now(pytz.utc)
+
+ notification_date = instance.notification_sent_datetime
+ start_date = clean_input.get("start_date")
+ end_date = clean_input.get("end_date")
+
+ if not start_date and not end_date:
+ return
+
+ send_notification = False
+ for date in [start_date, end_date]:
+ if (
+ date
+ and date <= now
+ and (notification_date is None or notification_date < date)
+ ):
+ send_notification = True
+
+ # we always need to notify if the end_date is in the past and previously
+ # the end date was not set
+ if end_date and end_date <= now and previous_end_date is None:
+ send_notification = True
+
+ if send_notification:
+ manager.sale_toggle(instance, catalogue)
+ instance.notification_sent_datetime = now
+ instance.save(update_fields=["notification_sent_datetime"])
diff --git a/saleor/graphql/discount/tests/test_discount.py b/saleor/graphql/discount/tests/test_discount.py
index 343b79c87c..1b1cec2a60 100644
--- a/saleor/graphql/discount/tests/test_discount.py
+++ b/saleor/graphql/discount/tests/test_discount.py
@@ -1142,157 +1142,6 @@ def test_voucher_remove_no_catalogues(
assert voucher.variants.exists()
-@patch("saleor.plugins.manager.PluginsManager.sale_created")
-def test_create_sale(
- created_webhook_mock, staff_api_client, permission_manage_discounts, product_list
-):
- query = """
- mutation saleCreate(
- $type: DiscountValueTypeEnum, $name: String, $value: PositiveDecimal,
- $startDate: DateTime, $endDate: DateTime, $products: [ID!]) {
- saleCreate(input: {
- name: $name, type: $type, value: $value,
- startDate: $startDate, endDate: $endDate, products: $products}) {
- sale {
- type
- name
- startDate
- endDate
- }
- errors {
- field
- code
- message
- }
- }
- }
- """
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
- product_ids = [
- graphene.Node.to_global_id("Product", product.id) for product in product_list
- ]
- variables = {
- "name": "test sale",
- "type": DiscountValueTypeEnum.FIXED.name,
- "startDate": start_date.isoformat(),
- "endDate": end_date.isoformat(),
- "products": product_ids,
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_discounts]
- )
- content = get_graphql_content(response)
- data = content["data"]["saleCreate"]["sale"]
-
- assert data["type"] == DiscountValueType.FIXED.upper()
- assert data["name"] == "test sale"
- assert data["startDate"] == start_date.isoformat()
- assert data["endDate"] == end_date.isoformat()
-
- sale = Sale.objects.filter(name="test sale").get()
- current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
- created_webhook_mock.assert_called_once_with(sale, current_catalogue)
-
-
-def test_create_sale_with_enddate_before_startdate(
- staff_api_client, permission_manage_discounts
-):
- query = """
- mutation saleCreate(
- $type: DiscountValueTypeEnum, $name: String, $value: PositiveDecimal,
- $startDate: DateTime, $endDate: DateTime) {
- saleCreate(input: {
- name: $name, type: $type, value: $value,
- startDate: $startDate, endDate: $endDate}) {
- sale {
- type
- name
- startDate
- endDate
- }
- errors {
- field
- code
- message
- }
- }
- }
- """
- start_date = timezone.now() + timedelta(days=365)
- end_date = timezone.now() - timedelta(days=365)
- variables = {
- "name": "test sale",
- "type": DiscountValueTypeEnum.FIXED.name,
- "startDate": start_date.isoformat(),
- "endDate": end_date.isoformat(),
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_discounts]
- )
- content = get_graphql_content(response)
- assert content["data"]["saleCreate"]["errors"]
- errors = content["data"]["saleCreate"]["errors"]
- assert len(errors) == 1
- assert errors[0]["field"] == "endDate"
- assert errors[0]["code"] == DiscountErrorCode.INVALID.name
- assert errors
-
-
-@patch("saleor.plugins.manager.PluginsManager.sale_updated")
-def test_update_sale(
- updated_webhook_mock,
- staff_api_client,
- sale,
- permission_manage_discounts,
- product_list,
-):
- query = """
- mutation saleUpdate($type: DiscountValueTypeEnum, $id: ID!, $products: [ID!]) {
- saleUpdate(id: $id, input: {type: $type, products: $products}) {
- errors {
- field
- code
- message
- }
- sale {
- type
- }
- }
- }
- """
-
- # Set discount value type to 'fixed' and change it in mutation
- sale.type = DiscountValueType.FIXED
- sale.save()
- previous_catalogue = convert_catalogue_info_to_global_ids(
- fetch_catalogue_info(sale)
- )
- product_ids = [
- graphene.Node.to_global_id("Product", product.id) for product in product_list
- ]
- variables = {
- "id": graphene.Node.to_global_id("Sale", sale.id),
- "type": DiscountValueTypeEnum.PERCENTAGE.name,
- "products": product_ids,
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_discounts]
- )
- current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
-
- content = get_graphql_content(response)
- data = content["data"]["saleUpdate"]["sale"]
- assert data["type"] == DiscountValueType.PERCENTAGE.upper()
-
- updated_webhook_mock.assert_called_once_with(
- sale, previous_catalogue, current_catalogue
- )
-
-
@patch("saleor.plugins.manager.PluginsManager.sale_deleted")
def test_sale_delete_mutation(
deleted_webhook_mock, staff_api_client, sale, permission_manage_discounts
diff --git a/saleor/graphql/discount/tests/test_sale_create.py b/saleor/graphql/discount/tests/test_sale_create.py
new file mode 100644
index 0000000000..271e342249
--- /dev/null
+++ b/saleor/graphql/discount/tests/test_sale_create.py
@@ -0,0 +1,258 @@
+from datetime import timedelta
+from unittest.mock import patch
+
+import graphene
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ....discount import DiscountValueType
+from ....discount.error_codes import DiscountErrorCode
+from ....discount.models import Sale
+from ....discount.utils import fetch_catalogue_info
+from ...tests.utils import get_graphql_content
+from ..enums import DiscountValueTypeEnum
+from ..mutations.utils import convert_catalogue_info_to_global_ids
+
+SALE_CREATE_MUTATION = """
+ mutation saleCreate($input: SaleInput!) {
+ saleCreate(input: $input) {
+ sale {
+ type
+ name
+ startDate
+ endDate
+ }
+ errors {
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_created")
+def test_create_sale(
+ created_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ permission_manage_discounts,
+ product_list,
+):
+ # given
+ query = SALE_CREATE_MUTATION
+ start_date = timezone.now() - timedelta(days=365)
+ end_date = timezone.now() + timedelta(days=365)
+ product_ids = [
+ graphene.Node.to_global_id("Product", product.id) for product in product_list
+ ]
+ variables = {
+ "input": {
+ "name": "test sale",
+ "type": DiscountValueTypeEnum.FIXED.name,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "products": product_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["saleCreate"]["sale"]
+
+ assert data["type"] == DiscountValueType.FIXED.upper()
+ assert data["name"] == "test sale"
+ assert data["startDate"] == start_date.isoformat()
+ assert data["endDate"] == end_date.isoformat()
+
+ sale = Sale.objects.filter(name="test sale").get()
+ assert sale.notification_sent_datetime == timezone.now()
+
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+ created_webhook_mock.assert_called_once_with(sale, current_catalogue)
+ sale_toggle_mock.assert_called_once_with(sale, current_catalogue)
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_created")
+def test_create_sale_only_start_date(
+ created_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ permission_manage_discounts,
+ product_list,
+):
+ # given
+ query = SALE_CREATE_MUTATION
+ start_date = timezone.now() - timedelta(days=10)
+ product_ids = [
+ graphene.Node.to_global_id("Product", product.id) for product in product_list
+ ]
+ variables = {
+ "input": {
+ "name": "test sale",
+ "type": DiscountValueTypeEnum.FIXED.name,
+ "startDate": start_date.isoformat(),
+ "products": product_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["saleCreate"]["sale"]
+
+ assert data["type"] == DiscountValueType.FIXED.upper()
+ assert data["name"] == "test sale"
+ assert data["startDate"] == start_date.isoformat()
+ assert not data["endDate"]
+
+ sale = Sale.objects.filter(name="test sale").get()
+ assert sale.notification_sent_datetime == timezone.now()
+
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+ created_webhook_mock.assert_called_once_with(sale, current_catalogue)
+ sale_toggle_mock.assert_called_once_with(sale, current_catalogue)
+
+
+def test_create_sale_with_enddate_before_startdate(
+ staff_api_client, permission_manage_discounts
+):
+ # given
+ query = SALE_CREATE_MUTATION
+ start_date = timezone.now() + timedelta(days=365)
+ end_date = timezone.now() - timedelta(days=365)
+ variables = {
+ "input": {
+ "name": "test sale",
+ "type": DiscountValueTypeEnum.FIXED.name,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["saleCreate"]["errors"]
+ errors = content["data"]["saleCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "endDate"
+ assert errors[0]["code"] == DiscountErrorCode.INVALID.name
+
+
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_created")
+def test_create_sale_start_date_and_end_date_before_current_date(
+ created_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ permission_manage_discounts,
+ product_list,
+):
+ """Ensure the notification is sent when the sale is created with start
+ and end date that already passed."""
+ # given
+ query = SALE_CREATE_MUTATION
+ start_date = timezone.now() - timedelta(days=20)
+ end_date = timezone.now() - timedelta(days=10)
+ product_ids = [
+ graphene.Node.to_global_id("Product", product.id) for product in product_list
+ ]
+ variables = {
+ "input": {
+ "name": "test sale",
+ "type": DiscountValueTypeEnum.FIXED.name,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "products": product_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["saleCreate"]["sale"]
+
+ assert data["type"] == DiscountValueType.FIXED.upper()
+ assert data["name"] == "test sale"
+ assert data["startDate"] == start_date.isoformat()
+ assert data["endDate"] == end_date.isoformat()
+
+ sale = Sale.objects.filter(name="test sale").get()
+ assert sale.notification_sent_datetime is None
+
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+ created_webhook_mock.assert_called_once_with(sale, current_catalogue)
+ sale_toggle_mock.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_created")
+def test_create_sale_start_date_and_end_date_after_current_date(
+ created_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ permission_manage_discounts,
+ product_list,
+):
+ """Ensure the notification is not sent when the sale is created with start
+ and end date in the feature."""
+ # given
+ query = SALE_CREATE_MUTATION
+ start_date = timezone.now() + timedelta(days=10)
+ end_date = timezone.now() + timedelta(days=20)
+ product_ids = [
+ graphene.Node.to_global_id("Product", product.id) for product in product_list
+ ]
+ variables = {
+ "input": {
+ "name": "test sale",
+ "type": DiscountValueTypeEnum.FIXED.name,
+ "startDate": start_date.isoformat(),
+ "endDate": end_date.isoformat(),
+ "products": product_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["saleCreate"]["sale"]
+
+ assert data["type"] == DiscountValueType.FIXED.upper()
+ assert data["name"] == "test sale"
+ assert data["startDate"] == start_date.isoformat()
+ assert data["endDate"] == end_date.isoformat()
+
+ sale = Sale.objects.filter(name="test sale").get()
+ assert sale.notification_sent_datetime is None
+
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+ created_webhook_mock.assert_called_once_with(sale, current_catalogue)
+ sale_toggle_mock.assert_not_called()
diff --git a/saleor/graphql/discount/tests/test_sale_update.py b/saleor/graphql/discount/tests/test_sale_update.py
new file mode 100644
index 0000000000..709003f976
--- /dev/null
+++ b/saleor/graphql/discount/tests/test_sale_update.py
@@ -0,0 +1,378 @@
+from datetime import timedelta
+from unittest.mock import patch
+
+import graphene
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ....discount import DiscountValueType
+from ....discount.utils import fetch_catalogue_info
+from ...tests.utils import get_graphql_content
+from ..enums import DiscountValueTypeEnum
+from ..mutations.utils import convert_catalogue_info_to_global_ids
+
+SALE_UPDATE_MUTATION = """
+ mutation saleUpdate($id: ID!, $input: SaleInput!) {
+ saleUpdate(id: $id, input: $input) {
+ errors {
+ field
+ code
+ message
+ }
+ sale {
+ type
+ startDate
+ endDate
+ }
+ }
+ }
+"""
+
+
+@patch("saleor.plugins.manager.PluginsManager.sale_updated")
+def test_update_sale(
+ updated_webhook_mock,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+ product_list,
+):
+ # given
+ query = SALE_UPDATE_MUTATION
+
+ # Set discount value type to 'fixed' and change it in mutation
+ sale.type = DiscountValueType.FIXED
+ sale.save(update_fields=["type"])
+ previous_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+ product_ids = [
+ graphene.Node.to_global_id("Product", product.id) for product in product_list
+ ]
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {
+ "type": DiscountValueTypeEnum.PERCENTAGE.name,
+ "products": product_ids,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["saleUpdate"]["sale"]
+ assert data["type"] == DiscountValueType.PERCENTAGE.upper()
+
+ updated_webhook_mock.assert_called_once_with(
+ sale, previous_catalogue, current_catalogue
+ )
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_updated")
+def test_update_sale_start_date_after_current_date_notification_not_sent(
+ updated_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+):
+ """Ensure the notification is not sent when the start date is set after the current
+ date.
+ """
+ # given
+ query = SALE_UPDATE_MUTATION
+
+ sale.notification_sent_datetime = None
+ sale.save(update_fields=["notification_sent_datetime"])
+
+ previous_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+ start_date = timezone.now() + timedelta(days=1)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {"startDate": start_date},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+
+ # then
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+
+ content = get_graphql_content(response)
+ data = content["data"]["saleUpdate"]["sale"]
+
+ assert data["startDate"] == start_date.isoformat()
+
+ sale.refresh_from_db()
+ assert sale.notification_sent_datetime is None
+
+ updated_webhook_mock.assert_called_once_with(
+ sale, previous_catalogue, current_catalogue
+ )
+ sale_toggle_mock.assert_not_called()
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_updated")
+def test_update_sale_start_date_before_current_date_notification_already_sent(
+ updated_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+):
+ """Ensure the notification is not sent when the start date is set before
+ current date and notification was already sent.
+ """
+ # given
+ query = SALE_UPDATE_MUTATION
+ now = timezone.now()
+
+ # Set discount value type to 'fixed' and change it in mutation
+ sale.type = DiscountValueType.FIXED
+ notification_sent_datetime = now - timedelta(minutes=5)
+ sale.notification_sent_datetime = notification_sent_datetime
+ sale.save(update_fields=["type", "notification_sent_datetime"])
+
+ previous_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+ start_date = timezone.now() - timedelta(days=1)
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {"startDate": start_date},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["saleUpdate"]["sale"]
+ assert data["startDate"] == start_date.isoformat()
+
+ sale.refresh_from_db()
+ assert sale.notification_sent_datetime == notification_sent_datetime
+
+ updated_webhook_mock.assert_called_once_with(
+ sale, previous_catalogue, current_catalogue
+ )
+ sale_toggle_mock.assert_not_called()
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_updated")
+def test_update_sale_start_date_before_current_date_notification_sent(
+ updated_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+):
+ """Ensure the sale_toggle notification is sent and the notification date is set
+ when the start date is set before current date and the notification hasn't been sent
+ before.
+ """
+
+ query = SALE_UPDATE_MUTATION
+
+ # Set discount value type to 'fixed' and change it in mutation
+ sale.type = DiscountValueType.FIXED
+ sale.notification_sent_datetime = None
+ sale.save(update_fields=["type", "notification_sent_datetime"])
+
+ previous_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+ start_date = timezone.now() - timedelta(days=1)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {"startDate": start_date},
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+
+ content = get_graphql_content(response)
+ data = content["data"]["saleUpdate"]["sale"]
+ assert data["startDate"] == start_date.isoformat()
+
+ sale.refresh_from_db()
+ assert sale.notification_sent_datetime == timezone.now()
+
+ updated_webhook_mock.assert_called_once_with(
+ sale, previous_catalogue, current_catalogue
+ )
+ sale_toggle_mock.assert_called_once_with(sale, current_catalogue)
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_updated")
+def test_update_sale_end_date_after_current_date_notification_not_sent(
+ updated_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+):
+ """Ensure the notification is not sent when the end date is set after
+ the current date.
+ """
+ # given
+ query = SALE_UPDATE_MUTATION
+
+ previous_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+ end_date = timezone.now() + timedelta(days=1)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {"endDate": end_date},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+
+ # then
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+
+ content = get_graphql_content(response)
+ data = content["data"]["saleUpdate"]["sale"]
+
+ assert data["endDate"] == end_date.isoformat()
+
+ sale.refresh_from_db()
+ assert sale.notification_sent_datetime is None
+
+ updated_webhook_mock.assert_called_once_with(
+ sale, previous_catalogue, current_catalogue
+ )
+ sale_toggle_mock.assert_not_called()
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_updated")
+def test_update_sale_end_date_before_current_date_notification_already_sent(
+ updated_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+):
+ """Ensure the notification is sent when the end date is set before
+ current date, the notification was already sent but the end date was not set before.
+ It means we need to notify about ending the sale.
+ """
+ # given
+ query = SALE_UPDATE_MUTATION
+
+ now = timezone.now()
+
+ # Set discount value type to 'fixed' and change it in mutation
+ sale.type = DiscountValueType.FIXED
+ notification_sent_datetime = now - timedelta(minutes=5)
+ sale.notification_sent_datetime = notification_sent_datetime
+ sale.save(update_fields=["type", "notification_sent_datetime"])
+
+ previous_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+ end_date = now - timedelta(days=1)
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {"endDate": end_date},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["saleUpdate"]["sale"]
+ assert data["endDate"] == end_date.isoformat()
+
+ sale.refresh_from_db()
+ assert sale.notification_sent_datetime == now
+
+ updated_webhook_mock.assert_called_once_with(
+ sale, previous_catalogue, current_catalogue
+ )
+ sale_toggle_mock.assert_called_once_with(sale, current_catalogue)
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.plugins.manager.PluginsManager.sale_toggle")
+@patch("saleor.plugins.manager.PluginsManager.sale_updated")
+def test_update_sale_end_date_before_current_date_notification_sent(
+ updated_webhook_mock,
+ sale_toggle_mock,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+):
+ """Ensure the sale_toggle notification is sent and the notification date is set
+ when the end date is set before current date and the notification hasn't been sent
+ before.
+ """
+
+ query = SALE_UPDATE_MUTATION
+
+ # Set discount value type to 'fixed' and change it in mutation
+ sale.type = DiscountValueType.FIXED
+ sale.notification_sent_datetime = None
+ sale.save(update_fields=["type", "notification_sent_datetime"])
+
+ previous_catalogue = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+ end_date = timezone.now() - timedelta(days=1)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {"endDate": end_date},
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+
+ content = get_graphql_content(response)
+ data = content["data"]["saleUpdate"]["sale"]
+ assert data["endDate"] == end_date.isoformat()
+
+ sale.refresh_from_db()
+ assert sale.notification_sent_datetime == timezone.now()
+
+ updated_webhook_mock.assert_called_once_with(
+ sale, previous_catalogue, current_catalogue
+ )
+ sale_toggle_mock.assert_called_once_with(sale, current_catalogue)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b00674ff74..acc6f0a413 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1448,6 +1448,7 @@ enum WebhookEventTypeEnum {
SALE_CREATED
SALE_UPDATED
SALE_DELETED
+ SALE_TOGGLE
"""An invoice for order requested."""
INVOICE_REQUESTED
@@ -1743,6 +1744,7 @@ enum WebhookEventTypeAsyncEnum {
SALE_CREATED
SALE_UPDATED
SALE_DELETED
+ SALE_TOGGLE
"""An invoice for order requested."""
INVOICE_REQUESTED
@@ -2386,6 +2388,7 @@ enum WebhookSampleEventTypeEnum {
SALE_CREATED
SALE_UPDATED
SALE_DELETED
+ SALE_TOGGLE
INVOICE_REQUESTED
INVOICE_DELETED
INVOICE_SENT
@@ -22256,6 +22259,39 @@ type SaleDeleted implements Event {
): Sale
}
+"""
+The event informs about the start or end of the sale.
+
+Added in Saleor 3.5.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type SaleToggle implements Event {
+ """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 sale the event relates to.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ sale(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
+ ): Sale
+}
+
type InvoiceRequested implements Event {
"""Time of the event."""
issuedAt: DateTime
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index edc7f042bb..c66c8b85d3 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -124,6 +124,7 @@ class Event(graphene.Interface):
WebhookEventAsyncType.SALE_CREATED: SaleCreated,
WebhookEventAsyncType.SALE_UPDATED: SaleUpdated,
WebhookEventAsyncType.SALE_DELETED: SaleDeleted,
+ WebhookEventAsyncType.SALE_TOGGLE: SaleToggle,
WebhookEventAsyncType.INVOICE_REQUESTED: InvoiceRequested,
WebhookEventAsyncType.INVOICE_DELETED: InvoiceDeleted,
WebhookEventAsyncType.INVOICE_SENT: InvoiceSent,
@@ -663,6 +664,24 @@ class SaleDeleted(ObjectType, SaleBase):
interfaces = (Event,)
+class SaleToggle(ObjectType, SaleBase):
+ sale = graphene.Field(
+ "saleor.graphql.discount.types.Sale",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description="The sale the event relates to." + ADDED_IN_35 + PREVIEW_FEATURE,
+ )
+
+ class Meta:
+ description = (
+ "The event informs about the start or end of the sale."
+ + ADDED_IN_35
+ + PREVIEW_FEATURE
+ )
+ interfaces = (Event,)
+
+
class InvoiceBase(AbstractType):
invoice = graphene.Field(
"saleor.graphql.invoice.types.Invoice",
@@ -1157,6 +1176,7 @@ SUBSCRIPTION_EVENTS_TYPES = [
SaleCreated,
SaleUpdated,
SaleDeleted,
+ SaleToggle,
InvoiceRequested,
InvoiceDeleted,
InvoiceSent,
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 42b547a748..2860e5d0ae 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -696,6 +696,12 @@ class PluginsManager(PaymentInterface):
"sale_updated", default_value, sale, previous_catalogue, current_catalogue
)
+ def sale_toggle(self, sale: "Sale", catalogue):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "sale_toggle", default_value, sale, catalogue
+ )
+
def invoice_request(
self, order: "Order", invoice: "Invoice", number: Optional[str]
):
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 0d92fc224a..bcb30c4d5e 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -238,6 +238,14 @@ class PluginSample(BasePlugin):
):
return sale, previous_catalogue
+ def sale_toggle(
+ self,
+ sale: "Sale",
+ catalogue: DefaultDict[str, Set[str]],
+ previous_value: Any,
+ ):
+ return sale, catalogue
+
def get_checkout_line_tax_rate(
self,
checkout_info: "CheckoutInfo",
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 8fac6ef8a5..33ff711bf2 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -604,6 +604,18 @@ def test_manager_sale_deleted(sale):
assert previous_catalogue == previous_catalogue_returned
+def test_manager_sale_toggle(sale):
+ plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+
+ current_catalogue = convert_catalogue_info_to_global_ids(fetch_catalogue_info(sale))
+ sale_returned, current_catalogue_returned = PluginsManager(
+ plugins=plugins
+ ).sale_toggle(sale, current_catalogue)
+
+ assert sale == sale_returned
+ assert current_catalogue == current_catalogue_returned
+
+
@pytest.mark.parametrize(
"plugins, amount",
[(["saleor.plugins.tests.sample_plugins.PluginSample"], "15.0"), ([], "0")],
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index d5aa43a022..b6254de162 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -30,6 +30,7 @@ from ...webhook.payloads import (
generate_product_variant_with_stock_payload,
generate_requestor,
generate_sale_payload,
+ generate_sale_toggle_payload,
generate_transaction_action_request_payload,
generate_translation_payload,
)
@@ -478,6 +479,23 @@ class WebhookPlugin(BasePlugin):
sale_data, event_type, webhooks, sale, self.requestor
)
+ def sale_toggle(
+ self,
+ sale: "Sale",
+ catalogue: DefaultDict[str, Set[str]],
+ previous_value: Any,
+ ):
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.SALE_TOGGLE
+ if webhooks := get_webhooks_for_event(event_type):
+ sale_data = generate_sale_toggle_payload(
+ sale, catalogue=catalogue, requestor=self.requestor
+ )
+ trigger_webhooks_async(
+ sale_data, event_type, webhooks, sale, self.requestor
+ )
+
def invoice_request(
self,
order: "Order",
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index 416e169a9e..f0835f4cfa 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -432,6 +432,13 @@ def subscription_sale_deleted_webhook(subscription_webhook):
)
+def subscription_sale_toggle_webhook(subscription_webhook):
+ return subscription_webhook(
+ subscription_queries.SALE_TOGGLE, WebhookEventAsyncType.SALE_TOGGLE
+ )
+
+
@pytest.fixture
def subscription_invoice_requested_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 a39cdcba9e..36a1aaade8 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -843,6 +843,22 @@ SALE_DELETED = (
"""
)
+
+SALE_TOGGLE = (
+ fragments.SALE_DETAILS
+ + """
+ subscription{
+ event{
+ ...on SaleToggle{
+ sale{
+ ...SaleDetails
+ }
+ }
+ }
+ }
+"""
+)
+
INVOICE_REQUESTED = (
fragments.INVOICE_DETAILS
+ """
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 2591a06c53..acea4ce158 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
@@ -1117,6 +1117,21 @@ def test_sale_deleted(sale, subscription_sale_deleted_webhook):
assert deliveries[0].webhook == webhooks[0]
+def test_sale_toggle(sale, subscription_sale_toggle_webhook):
+ # given
+ webhooks = [subscription_sale_toggle_webhook]
+ event_type = WebhookEventAsyncType.SALE_TOGGLE
+ expected_payload = generate_sale_payload(sale)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, sale, webhooks)
+
+ # then
+ assert deliveries[0].payload.payload == json.dumps(expected_payload)
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_invoice_requested(fulfilled_order, subscription_invoice_requested_webhook):
# given
webhooks = [subscription_invoice_requested_webhook]
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 4583a2a7af..bd76698118 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -45,6 +45,7 @@ from ....webhook.payloads import (
generate_product_variant_payload,
generate_product_variant_with_stock_payload,
generate_sale_payload,
+ generate_sale_toggle_payload,
generate_transaction_action_request_payload,
)
from ....webhook.utils import get_webhooks_for_event
@@ -1021,6 +1022,30 @@ def test_sale_deleted(
)
+@freeze_time("2020-10-10 10:10")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_sale_toggle(
+ mocked_webhook_trigger, mocked_get_webhooks_for_event, any_webhook, settings, sale
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ sale_catalogue_info = convert_catalogue_info_to_global_ids(
+ fetch_catalogue_info(sale)
+ )
+
+ # when
+ manager.sale_toggle(sale, catalogue=sale_catalogue_info)
+
+ # then
+ expected_data = generate_sale_toggle_payload(sale, catalogue=sale_catalogue_info)
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data, WebhookEventAsyncType.SALE_TOGGLE, [any_webhook], sale, None
+ )
+
+
@mock.patch("saleor.plugins.webhook.plugin.send_webhook_request_async.delay")
def test_event_delivery_retry(mocked_webhook_send, event_delivery, settings):
# given
diff --git a/saleor/settings.py b/saleor/settings.py
index b15f426875..e3f0949e96 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -22,6 +22,7 @@ from sentry_sdk.integrations.logging import ignore_logger
from . import PatchedSubscriberExecutionContext, __version__
from .core.languages import LANGUAGES as CORE_LANGUAGES
+from .core.schedules import sale_webhook_schedule
def get_list(text):
@@ -566,6 +567,10 @@ CELERY_BEAT_SCHEDULE = {
"task": "saleor.csv.tasks.delete_old_export_files",
"schedule": crontab(hour=1, minute=0),
},
+ "send-sale-toggle-notifications": {
+ "task": "saleor.discount.tasks.send_sale_toggle_notifications",
+ "schedule": sale_webhook_schedule(),
+ },
}
EVENT_PAYLOAD_DELETE_PERIOD = timedelta(
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 89d4208f83..e7a4fd5eee 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -72,6 +72,7 @@ class WebhookEventAsyncType:
SALE_CREATED = "sale_created"
SALE_UPDATED = "sale_updated"
SALE_DELETED = "sale_deleted"
+ SALE_TOGGLE = "sale_toggle"
INVOICE_REQUESTED = "invoice_requested"
INVOICE_DELETED = "invoice_deleted"
@@ -182,6 +183,7 @@ class WebhookEventAsyncType:
SALE_CREATED: "Sale created",
SALE_UPDATED: "Sale updated",
SALE_DELETED: "Sale deleted",
+ SALE_TOGGLE: "Sale toggle",
INVOICE_REQUESTED: "Invoice requested",
INVOICE_DELETED: "Invoice deleted",
INVOICE_SENT: "Invoice sent",
@@ -275,6 +277,7 @@ class WebhookEventAsyncType:
(SALE_CREATED, DISPLAY_LABELS[SALE_CREATED]),
(SALE_UPDATED, DISPLAY_LABELS[SALE_UPDATED]),
(SALE_DELETED, DISPLAY_LABELS[SALE_DELETED]),
+ (SALE_TOGGLE, DISPLAY_LABELS[SALE_TOGGLE]),
(INVOICE_REQUESTED, DISPLAY_LABELS[INVOICE_REQUESTED]),
(INVOICE_DELETED, DISPLAY_LABELS[INVOICE_DELETED]),
(INVOICE_SENT, DISPLAY_LABELS[INVOICE_SENT]),
@@ -369,6 +372,7 @@ class WebhookEventAsyncType:
SALE_CREATED: DiscountPermissions.MANAGE_DISCOUNTS,
SALE_UPDATED: DiscountPermissions.MANAGE_DISCOUNTS,
SALE_DELETED: DiscountPermissions.MANAGE_DISCOUNTS,
+ SALE_TOGGLE: DiscountPermissions.MANAGE_DISCOUNTS,
INVOICE_REQUESTED: OrderPermissions.MANAGE_ORDERS,
INVOICE_DELETED: OrderPermissions.MANAGE_ORDERS,
INVOICE_SENT: OrderPermissions.MANAGE_ORDERS,
@@ -541,6 +545,7 @@ SUBSCRIBABLE_EVENTS = [
WebhookEventAsyncType.SALE_CREATED,
WebhookEventAsyncType.SALE_UPDATED,
WebhookEventAsyncType.SALE_DELETED,
+ WebhookEventAsyncType.SALE_TOGGLE,
WebhookEventAsyncType.INVOICE_REQUESTED,
WebhookEventAsyncType.INVOICE_DELETED,
WebhookEventAsyncType.INVOICE_SENT,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 1b36bea3e4..1645d5be1d 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -422,6 +422,28 @@ def generate_sale_payload(
)
+@traced_payload_generator
+def generate_sale_toggle_payload(
+ sale: "Sale",
+ catalogue: DefaultDict[str, Set[str]],
+ requestor: Optional["RequestorOrLazyObject"] = None,
+):
+ serializer = PayloadSerializer()
+ sale_fields = ("id",)
+
+ extra_dict_data = {key: list(ids) for key, ids in catalogue.items()}
+ extra_dict_data["meta"] = generate_meta(
+ requestor_data=generate_requestor(requestor)
+ )
+ extra_dict_data["is_active"] = sale.is_active()
+
+ return serializer.serialize(
+ [sale],
+ fields=sale_fields,
+ extra_dict_data=extra_dict_data,
+ )
+
+
@traced_payload_generator
def generate_invoice_payload(
invoice: "Invoice", requestor: Optional["RequestorOrLazyObject"] = None
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index a93b31368f..3c880cf0d0 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -50,6 +50,7 @@ from ..payloads import (
generate_product_variant_with_stock_payload,
generate_requestor,
generate_sale_payload,
+ generate_sale_toggle_payload,
generate_transaction_action_request_payload,
generate_translation_payload,
)
@@ -1145,6 +1146,26 @@ def test_generate_sale_payload_calculates_set_differences(sale):
assert set(payload["variants_removed"]) == {"ccc"}
+def test_generate_sale_toggle_payload(sale):
+ # given
+ current_info = {
+ "categories": {4, 2, 3},
+ "collections": set(),
+ "products": {4, 5, 6, 10, 20},
+ "variants": {"aaa", "bbb", "ddd"},
+ }
+
+ # when
+ payload = json.loads(generate_sale_toggle_payload(sale, current_info))[0]
+
+ # then
+ assert payload["is_active"] is True
+ assert set(payload["categories"]) == current_info["categories"]
+ assert not payload["collections"]
+ assert set(payload["products"]) == current_info["products"]
+ assert set(payload["variants"]) == current_info["variants"]
+
+
@freeze_time()
def test_generate_checkout_payload(
checkout_with_items,