Skip to content

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

Invoice events

Tomasz Szymanski61169f2d824d
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 9baada7979..e3a4bcf471 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -1,3 +1,5 @@
+import copy
+
import graphene
from django.core.exceptions import ValidationError
@@ -544,6 +546,9 @@ class RequestInvoice(BaseMutation):
info.context.plugins.invoice_request(
order=order, invoice=invoice, number=data.get("number")
)
+ events.invoice_requested_event(
+ user=info.context.user, order=order, number=data.get("number")
+ )
return RequestInvoice()
@@ -590,6 +595,12 @@ class CreateInvoice(ModelMutation):
invoice.order = instance
invoice.status = InvoiceStatus.READY
invoice.save()
+ events.invoice_created_event(
+ user=info.context.user,
+ invoice=invoice,
+ number=data["input"].get("number"),
+ url=data["input"].get("url"),
+ )
return CreateInvoice(invoice=invoice)
@@ -612,6 +623,7 @@ class RequestDeleteInvoice(ModelMutation):
invoice.status = InvoiceStatus.PENDING_DELETE
invoice.save()
info.context.plugins.invoice_delete(invoice)
+ events.invoice_requested_deletion(user=info.context.user, invoice=invoice)
return RequestDeleteInvoice()
@@ -626,6 +638,13 @@ class DeleteInvoice(ModelDeleteMutation):
error_type_class = InvoiceError
error_type_field = "invoice_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ invoice_pk = copy.copy(cls.get_instance(info, **data).pk)
+ response = super().perform_mutation(_root, info, **data)
+ events.invoice_deleted_event(user=info.context.user, invoice_id=invoice_pk)
+ return response
+
class UpdateInvoiceInput(graphene.InputObjectType):
number = graphene.String(description="Invoice number")
@@ -703,4 +722,5 @@ class SendInvoiceEmail(ModelMutation):
instance = cls.get_instance(info, **data)
cls.clean_instance(info, instance)
send_invoice.delay(instance.pk)
+ events.invoice_sent_event(user=info.context.user, invoice=instance)
return SendInvoiceEmail(invoice=instance)
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 30b7055ae2..4bbaeee712 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -103,3 +103,19 @@ class OrderEventsEmails:
(FULFILLMENT, "The fulfillment confirmation email was sent"),
(DIGITAL_LINKS, "The email containing the digital links was sent"),
]
+
+
+class InvoiceEvents:
+ REQUESTED = "requested"
+ REQUESTED_DELETION = "requested_deletion"
+ CREATED = "created"
+ DELETED = "deleted"
+ SENT = "sent"
+
+ CHOICES = [
+ (REQUESTED, "The invoice was requested"),
+ (REQUESTED_DELETION, "The invoice was requested for deletion"),
+ (CREATED, "The invoice was created"),
+ (DELETED, "The invoice was deleted"),
+ (SENT, "The invoice has been sent"),
+ ]
diff --git a/saleor/order/events.py b/saleor/order/events.py
index b8194577ea..03e0bc5cd7 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -3,10 +3,10 @@ from typing import Dict, List, Optional, Tuple, Union
from ..account import events as account_events
from ..account.models import User
-from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
+from ..order.models import Fulfillment, FulfillmentLine, Invoice, Order, OrderLine
from ..payment.models import Payment
from . import OrderEvents, OrderEventsEmails
-from .models import OrderEvent
+from .models import InvoiceEvent, InvoiceEvents, OrderEvent
UserType = Optional[User]
@@ -95,6 +95,53 @@ def draft_order_removed_products_event(
)
+def invoice_requested_event(
+ *, user: UserType, order: Order, number: str
+) -> InvoiceEvent:
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.REQUESTED,
+ user=user,
+ order=order,
+ parameters={"number": number},
+ )
+
+
+def invoice_requested_deletion(*, user: UserType, invoice: Invoice) -> InvoiceEvent:
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.REQUESTED_DELETION,
+ user=user,
+ invoice=invoice,
+ order=invoice.order,
+ )
+
+
+def invoice_created_event(
+ *, user: UserType, invoice: Invoice, number: str, url: str
+) -> InvoiceEvent:
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.CREATED,
+ user=user,
+ invoice=invoice,
+ order=invoice.order,
+ parameters={"number": number, "url": url},
+ )
+
+
+def invoice_deleted_event(*, user: UserType, invoice_id: int) -> InvoiceEvent:
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.DELETED, user=user, parameters={"invoice_id": invoice_id}
+ )
+
+
+def invoice_sent_event(*, user: UserType, invoice: Invoice) -> InvoiceEvent:
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.SENT,
+ user=user,
+ invoice=invoice,
+ parameters={"email": invoice.order.user.email}, # type: ignore
+ )
+
+
def order_created_event(
*, order: Order, user: UserType, from_draft=False
) -> OrderEvent:
diff --git a/saleor/order/migrations/0085_invoiceevent.py b/saleor/order/migrations/0085_invoiceevent.py
new file mode 100644
index 0000000000..0112e76115
--- /dev/null
+++ b/saleor/order/migrations/0085_invoiceevent.py
@@ -0,0 +1,95 @@
+# Generated by Django 3.0.6 on 2020-05-16 13:17
+
+import django.contrib.postgres.fields.jsonb
+import django.db.models.deletion
+import django.utils.timezone
+from django.conf import settings
+from django.db import migrations, models
+
+import saleor.core.utils.json_serializer
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ("order", "0084_auto_20200426_0647"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="InvoiceEvent",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "date",
+ models.DateTimeField(
+ default=django.utils.timezone.now, editable=False
+ ),
+ ),
+ (
+ "type",
+ models.CharField(
+ choices=[
+ ("requested", "The invoice was requested"),
+ (
+ "requested_deletion",
+ "The invoice was requested for deletion",
+ ),
+ ("created", "The invoice was created"),
+ ("deleted", "The invoice was deleted"),
+ ("sent", "The invoice has been sent"),
+ ],
+ max_length=255,
+ ),
+ ),
+ (
+ "parameters",
+ django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ ),
+ ),
+ (
+ "invoice",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="events",
+ to="order.Invoice",
+ ),
+ ),
+ (
+ "order",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="invoice_events",
+ to="order.Order",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ # flake8: noqa
+ options={"ordering": ("date",),},
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 29253f1b41..22db09dc7d 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -25,7 +25,7 @@ from ..giftcard.models import GiftCard
from ..graphql.order.enums import InvoiceStatus
from ..payment import ChargeStatus, TransactionKind
from ..shipping.models import ShippingMethod
-from . import FulfillmentStatus, OrderEvents, OrderStatus
+from . import FulfillmentStatus, InvoiceEvents, OrderEvents, OrderStatus
class OrderQueryset(models.QuerySet):
@@ -531,3 +531,33 @@ class Invoice(ModelWithMetadata):
if url is not None:
self.url = url
self.save()
+
+
+class InvoiceEvent(models.Model):
+ """Model used to store events that happened during the invoice lifecycle."""
+
+ date = models.DateTimeField(default=now, editable=False)
+ type = models.CharField(max_length=255, choices=InvoiceEvents.CHOICES)
+ invoice = models.ForeignKey(
+ Invoice, related_name="events", blank=True, null=True, on_delete=models.SET_NULL
+ )
+ order = models.ForeignKey(
+ Order,
+ related_name="invoice_events",
+ blank=True,
+ null=True,
+ on_delete=models.SET_NULL,
+ )
+ user = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ null=True,
+ on_delete=models.SET_NULL,
+ related_name="+",
+ )
+ parameters = JSONField(blank=True, default=dict, encoder=CustomJsonEncoder)
+
+ class Meta:
+ ordering = ("date",)
+
+ def __repr__(self):
+ return f"{self.__class__.__name__}(type={self.type!r}, user={self.user!r})"
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index 30191c9a71..b620ae66ad 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -23,7 +23,7 @@ from saleor.graphql.order.utils import validate_draft_order
from saleor.graphql.payment.types import PaymentChargeStatusEnum
from saleor.order import OrderStatus, events as order_events
from saleor.order.error_codes import InvoiceErrorCode, OrderErrorCode
-from saleor.order.models import Invoice, Order, OrderEvent
+from saleor.order.models import Invoice, InvoiceEvent, InvoiceEvents, Order, OrderEvent
from saleor.payment import ChargeStatus, CustomPaymentChoices, PaymentError
from saleor.payment.models import Payment
from saleor.plugins.manager import PluginsManager
@@ -3018,6 +3018,12 @@ def test_request_invoice(
invoice = Invoice.objects.filter(number=number, order=order.pk).first()
assert invoice
plugin_mock.assert_called_once_with(order, invoice, number, previous_value=None)
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.REQUESTED,
+ user=staff_api_client.user,
+ order=invoice.order,
+ parameters__number=number,
+ ).exists()
def test_request_invoice_no_number(staff_api_client, permission_manage_orders, order):
@@ -3051,6 +3057,12 @@ def test_request_delete_invoice(
invoice.refresh_from_db()
assert invoice.status == InvoiceStatus.PENDING_DELETE
plugin_mock.assert_called_once_with(invoice, previous_value=None)
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.REQUESTED_DELETION,
+ user=staff_api_client.user,
+ invoice=invoice,
+ order=invoice.order,
+ ).exists()
@patch("saleor.plugins.base_plugin.BasePlugin.invoice_delete")
@@ -3087,6 +3099,11 @@ def test_delete_invoice(staff_api_client, permission_manage_orders, order):
content = get_graphql_content(response)
assert not content["data"]["deleteInvoice"]["invoiceErrors"]
assert not Invoice.objects.filter(id=invoice.pk).exists()
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.DELETED,
+ user=staff_api_client.user,
+ parameters__invoice_id=invoice.id,
+ ).exists()
@patch("saleor.plugins.base_plugin.BasePlugin.invoice_delete")
@@ -3189,6 +3206,14 @@ def test_create_invoice(staff_api_client, permission_manage_orders, order):
assert invoice.url == content["data"]["createInvoice"]["invoice"]["url"]
assert invoice.number == content["data"]["createInvoice"]["invoice"]["number"]
assert invoice.status == InvoiceStatus.READY
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.CREATED,
+ user=staff_api_client.user,
+ invoice=invoice,
+ order=invoice.order,
+ parameters__number=number,
+ parameters__url=url,
+ ).exists()
def test_create_invoice_invalid_id(staff_api_client, permission_manage_orders):
@@ -3245,6 +3270,12 @@ def test_send_invoice(email_mock, staff_api_client, permission_manage_orders, or
content = get_graphql_content(response)
assert not content["data"]["sendInvoiceEmail"]["invoiceErrors"]
email_mock.assert_called_with(invoice.pk)
+ assert InvoiceEvent.objects.filter(
+ type=InvoiceEvents.SENT,
+ user=staff_api_client.user,
+ invoice=invoice,
+ parameters__email=order.user.email,
+ ).exists()
@patch("saleor.order.emails.send_invoice.delay")