Skip to content

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

Wrap digital download incrementing logic to make it more maintainable

NyanKiyoshi2c57e46714e9
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 7a0fee34aa..989584b65c 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -55,7 +55,7 @@ class OrderEvent(CountableDjangoObjectType):
)
class Meta:
- description = "History log of the order."
+ description = "History log of the customer."
model = models.OrderEvent
interfaces = [relay.Node]
only_fields = ["id"]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index d8a7667f26..164d5b7aa0 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -21,6 +21,7 @@ from versatileimagefield.fields import PPOIField, VersatileImageField
from saleor.core.utils import build_absolute_uri
+from ..account import events as customer_events
from ..core import TaxRateType
from ..core.exceptions import InsufficientStock
from ..core.models import PublishableModel, SortableModel
@@ -399,6 +400,18 @@ class DigitalContentUrl(models.Model):
self.token = str(uuid4()).replace("-", "")
super().save(force_insert, force_update, using, update_fields)
+ def increment_download_count(self):
+ self.download_num += 1
+ self.save(update_fields=["download_num"])
+
+ line = self.line
+ user = line.order.user if line else None
+
+ if user is not None:
+ customer_events.customer_downloaded_a_digital_link_event(
+ user=user, order_line=line
+ )
+
def get_absolute_url(self) -> str:
url = reverse("product:digital-product", kwargs={"token": str(self.token)})
return build_absolute_uri(url)
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 9ebc3a2db5..36aba37820 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -14,10 +14,8 @@ from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.urls import reverse
-from ..account import events as customer_events
from ..checkout.utils import set_checkout_cookie
from ..core.utils import serialize_decimal
-from ..order.models import OrderLine
from ..seo.schema.product import product_json_ld
from .filters import ProductCategoryFilter, ProductCollectionFilter
from .models import Category, DigitalContentUrl
@@ -112,8 +110,6 @@ def digital_product(request, token: str) -> Union[FileResponse, HttpResponseNotF
if not digital_content_url_is_valid(content_url):
return HttpResponseNotFound("Url is not valid anymore")
- line = content_url.line # type: OrderLine
- user = line.order.user if line else None
digital_content = content_url.content
digital_content.content_file.open()
opened_file = digital_content.content_file.file
@@ -126,14 +122,8 @@ def digital_product(request, token: str) -> Union[FileResponse, HttpResponseNotF
response["Content-Type"] = content_type
response["Content-Disposition"] = "attachment; {}".format(file_expr)
- content_url.download_num += 1
- content_url.save(update_fields=["download_num"])
-
- if user is not None:
- customer_events.customer_downloaded_a_digital_link_event(
- user=user, order_line=line
- )
+ content_url.increment_download_count()
return response
diff --git a/tests/checks/events.py b/tests/checks/events.py
index 158c4baaaa..5116ecbf8b 100644
--- a/tests/checks/events.py
+++ b/tests/checks/events.py
@@ -55,21 +55,6 @@ def were_customers_properly_deleted(
)
-def was_digital_good_download_event_properly_generated(
- download_event: customer_events.CustomerEvent,
- expected_order_line: Optional[customer_events.OrderLine],
- expected_user: Optional[customer_events.UserType],
-):
- """Ensure a digital good download event was properly generated
- during a given test case."""
-
- # Check that the event contains all the expected and valid data
- assert download_event.type == customer_events.CustomerEvents.DIGITAL_LINK_DOWNLOADED
- assert download_event.user == expected_user
- assert download_event.order == expected_order_line.order
- assert download_event.parameters == {"order_line_pk": expected_order_line.pk}
-
-
def assert_is_proper_customer_event_node(
received_node: Dict, event: customer_events.CustomerEvent
):
diff --git a/tests/test_product.py b/tests/test_product.py
index dbddb2762a..019c7adfc0 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -33,7 +33,6 @@ from saleor.product.utils.attributes import get_product_attributes_data
from saleor.product.utils.availability import get_product_availability_status
from saleor.product.utils.variants_picker import get_variant_picker_data
-from .checks import events as events_checks
from .utils import filter_products_by_attribute
@@ -771,18 +770,10 @@ def test_homepage_collection_render(client, site_settings, collection, product_l
assert products_in_context == products_available
[email protected]("should_user_be_deleted", (True, False))
-def test_digital_product_view(client, digital_content_url, should_user_be_deleted):
+def test_digital_product_view(client, digital_content_url):
"""Ensure a user (anonymous or not) can download a non-expired digital good
using its associated token and that all associated events
- are correctly generated.
-
- It also ensures that a digital order line that is associated to a deleted user
- can still be downloaded if non-expired."""
-
- expected_user = digital_content_url.line.order.user
- if should_user_be_deleted:
- digital_content_url.line.order.user.delete()
+ are correctly generated."""
url = digital_content_url.get_absolute_url()
response = client.get(url)
@@ -792,37 +783,50 @@ def test_digital_product_view(client, digital_content_url, should_user_be_delete
assert response["content-type"] == "image/jpeg"
assert response["content-disposition"] == 'attachment; filename="%s"' % filename
- # Ensure a line associated to a deleted user does not generate any event
- if should_user_be_deleted:
- assert not customer_events.CustomerEvent.objects.exists()
- return
-
- # Ensure an event was generated from downloading a digital good
- download_event = customer_events.CustomerEvent.objects.get()
-
- # Check that the event contains all the expected and valid data
- events_checks.was_digital_good_download_event_properly_generated(
- download_event,
- expected_order_line=digital_content_url.line,
- expected_user=expected_user,
- )
+ # Ensure an event was generated from downloading a digital good.
+ # The validity of this event is checked in test_digital_product_increment_download
+ assert customer_events.CustomerEvent.objects.exists()
-def test_digital_product_view_without_order_line(client, digital_content_url):
+ "is_user_null, is_line_null", ((False, False), (False, True), (True, True))
+)
+def test_digital_product_increment_download(
+ client,
+ customer_user,
+ digital_content_url: DigitalContentUrl,
+ is_user_null,
+ is_line_null,
+):
"""Ensure downloading a digital good is possible without it
- being associated to an order."""
-
- digital_content_url.line = None
- digital_content_url.save(update_fields=["line"])
-
- url = digital_content_url.get_absolute_url()
- response = client.get(url)
-
- assert response.status_code == 200
+ being associated to an order line/user."""
+
+ expected_user = customer_user
+
+ if is_line_null:
+ expected_user = None
+ digital_content_url.line = None
+ digital_content_url.save(update_fields=["line"])
+ elif is_user_null:
+ expected_user = None
+ digital_content_url.line.user = None
+ digital_content_url.line.save(update_fields=["user"])
+
+ expected_new_download_count = digital_content_url.download_num + 1
+ digital_content_url.increment_download_count()
+ assert digital_content_url.download_num == expected_new_download_count
+
+ if expected_user is None:
+ # Ensure an event was not generated from downloading a digital good
+ # as no user could be found
+ assert not customer_events.CustomerEvent.objects.exists()
+ return
- # Ensure an event was not generated from downloading a digital good
- # as no user could be found
- assert not customer_events.CustomerEvent.objects.exists()
+ download_event = customer_events.CustomerEvent.objects.get()
+ assert download_event.type == customer_events.CustomerEvents.DIGITAL_LINK_DOWNLOADED
+ assert download_event.user == expected_user
+ assert download_event.order == digital_content_url.line.order
+ assert download_event.parameters == {"order_line_pk": digital_content_url.line.pk}
def test_digital_product_view_url_downloaded_max_times(client, digital_content):