Skip to content

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

Handle invoice requests in plugins in 3.1 (#8800)

Jakubba127fcd7f36
diff --git a/saleor/graphql/invoice/mutations.py b/saleor/graphql/invoice/mutations.py
index 4c86b43374..508c7723c1 100644
--- a/saleor/graphql/invoice/mutations.py
+++ b/saleor/graphql/invoice/mutations.py
@@ -11,6 +11,7 @@ from ..core.mutations import ModelDeleteMutation, ModelMutation
from ..core.types.common import InvoiceError
from ..invoice.types import Invoice
from ..order.types import Order
+from .utils import is_event_active_for_any_plugin
class InvoiceRequest(ModelMutation):
@@ -61,15 +62,28 @@ class InvoiceRequest(ModelMutation):
)
cls.clean_order(order)
+ if not is_event_active_for_any_plugin(
+ "invoice_request", info.context.plugins.all_plugins
+ ):
+ raise ValidationError(
+ {
+ "orderId": ValidationError(
+ "No app or plugin is configured to handle invoice requests.",
+ code=InvoiceErrorCode.NO_INVOICE_PLUGIN,
+ )
+ }
+ )
+
shallow_invoice = models.Invoice.objects.create(
order=order,
number=data.get("number"),
)
+
invoice = info.context.plugins.invoice_request(
order=order, invoice=shallow_invoice, number=data.get("number")
)
- if invoice.status == JobStatus.SUCCESS:
+ if invoice and invoice.status == JobStatus.SUCCESS:
order_events.invoice_generated_event(
order=order,
user=info.context.user,
diff --git a/saleor/graphql/invoice/tests/test_invoice_request.py b/saleor/graphql/invoice/tests/test_invoice_request.py
index 9e5533496f..6149b7311f 100644
--- a/saleor/graphql/invoice/tests/test_invoice_request.py
+++ b/saleor/graphql/invoice/tests/test_invoice_request.py
@@ -41,9 +41,16 @@ def setup_dummy_gateways(settings):
return settings
+@patch(
+ "saleor.graphql.invoice.mutations.is_event_active_for_any_plugin", return_value=True
+)
@patch("saleor.plugins.manager.PluginsManager.invoice_request")
def test_invoice_request(
- plugin_mock, staff_api_client, permission_manage_orders, order
+ plugin_mock,
+ active_event_check_mock,
+ staff_api_client,
+ permission_manage_orders,
+ order,
):
dummy_invoice = Invoice.objects.create(order=order)
plugin_mock.return_value = dummy_invoice
@@ -121,14 +128,19 @@ def test_invoice_request_no_billing_address(
assert not OrderEvent.objects.filter(type=OrderEvents.INVOICE_REQUESTED).exists()
-def test_invoice_request_no_number(staff_api_client, permission_manage_orders, order):
+@patch(
+ "saleor.graphql.invoice.mutations.is_event_active_for_any_plugin", return_value=True
+)
+def test_invoice_request_no_number(
+ active_event_check_mock, staff_api_client, permission_manage_orders, order
+):
variables = {"orderId": graphene.Node.to_global_id("Order", order.pk)}
staff_api_client.post_graphql(
INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
)
invoice = Invoice.objects.get(order=order.pk)
assert invoice.number is None
- assert not OrderEvent.objects.filter(type=OrderEvents.INVOICE_REQUESTED).exists()
+ assert OrderEvent.objects.filter(type=OrderEvents.INVOICE_REQUESTED).exists()
def test_invoice_request_invalid_id(staff_api_client, permission_manage_orders):
@@ -140,3 +152,26 @@ def test_invoice_request_invalid_id(staff_api_client, permission_manage_orders):
error = content["data"]["invoiceRequest"]["errors"][0]
assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
assert error["field"] == "orderId"
+
+
+@patch(
+ "saleor.graphql.invoice.mutations.is_event_active_for_any_plugin",
+ return_value=False,
+)
+def test_invoice_request_no_invoice_plugin(
+ active_event_check_mock, order, permission_manage_orders, staff_api_client
+):
+ number = "01/12/2020/TEST"
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": number,
+ }
+ response = staff_api_client.post_graphql(
+ INVOICE_REQUEST_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not Invoice.objects.filter(number=number, order=order.pk).exists()
+ error = content["data"]["invoiceRequest"]["errors"][0]
+ assert error["field"] == "orderId"
+ assert error["code"] == InvoiceErrorCode.NO_INVOICE_PLUGIN.name
+ assert not OrderEvent.objects.filter(type=OrderEvents.INVOICE_REQUESTED).exists()
diff --git a/saleor/graphql/invoice/tests/test_invoice_utils.py b/saleor/graphql/invoice/tests/test_invoice_utils.py
index 8fd53dadba..1a8fc692c6 100644
--- a/saleor/graphql/invoice/tests/test_invoice_utils.py
+++ b/saleor/graphql/invoice/tests/test_invoice_utils.py
@@ -3,6 +3,7 @@ from unittest.mock import patch
from ....invoice.models import Invoice
from ....plugins.invoicing.utils import generate_invoice_number
+from ..utils import is_event_active_for_any_plugin
@patch("saleor.plugins.invoicing.utils.datetime")
@@ -23,3 +24,33 @@ def test_generate_invoice_number_old_invoice(datetime_mock, order):
def test_generate_invoice_number_no_existing_invoice(datetime_mock, order):
datetime_mock.now.return_value = datetime(2020, 7, 23, 12, 59, 59)
assert generate_invoice_number() == "1/07/2020"
+
+
+class MockInvoicePluginActive:
+ active = True
+
+ @staticmethod
+ def is_event_active(_):
+ return True
+
+
+class MockInvoicePluginInactive:
+ active = False
+
+ @staticmethod
+ def is_event_active(_):
+ return True
+
+
+def test_is_event_active_for_any_plugin_plugin_active():
+ result = is_event_active_for_any_plugin(
+ "event", [MockInvoicePluginActive(), MockInvoicePluginInactive()]
+ )
+ assert result is True
+
+
+def test_is_event_active_for_any_plugin_plugin_inactive():
+ result = is_event_active_for_any_plugin(
+ "event", [MockInvoicePluginInactive(), MockInvoicePluginInactive()]
+ )
+ assert result is False
diff --git a/saleor/graphql/invoice/utils.py b/saleor/graphql/invoice/utils.py
new file mode 100644
index 0000000000..c81d1f9a13
--- /dev/null
+++ b/saleor/graphql/invoice/utils.py
@@ -0,0 +1,4 @@
+def is_event_active_for_any_plugin(event: str, plugins_list):
+ return any(
+ [plugin.is_event_active(event) for plugin in plugins_list if plugin.active]
+ )
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 45ca211115..b3024ae56a 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2611,6 +2611,7 @@ enum InvoiceErrorCode {
NUMBER_NOT_SET
NOT_FOUND
INVALID_STATUS
+ NO_INVOICE_PLUGIN
}
type InvoiceRequest {
diff --git a/saleor/invoice/error_codes.py b/saleor/invoice/error_codes.py
index e7f057abff..eca2029cfb 100644
--- a/saleor/invoice/error_codes.py
+++ b/saleor/invoice/error_codes.py
@@ -9,3 +9,4 @@ class InvoiceErrorCode(Enum):
NUMBER_NOT_SET = "number_not_set"
NOT_FOUND = "not_found"
INVALID_STATUS = "invalid_status"
+ NO_INVOICE_PLUGIN = "no_invoice_plugin"
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index e244477b11..2aee712c9f 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -358,9 +358,11 @@ class BasePlugin:
invoice_delete: Callable[["Invoice", Any], Any]
# Trigger when invoice creation starts.
- #
+ # May return Invoice object.
# Overwrite to create invoice with proper data, call invoice.update_invoice.
- invoice_request: Callable[["Order", "Invoice", Union[str, NoneType], Any], Any]
+ invoice_request: Callable[
+ ["Order", "Invoice", Union[str, NoneType], Any], Optional["Invoice"]
+ ]
# Trigger after invoice is sent.
invoice_sent: Callable[["Invoice", str, Any], Any]
@@ -665,3 +667,6 @@ class BasePlugin:
# Let's add a translated descriptions and labels
self._append_config_structure(configuration)
return configuration
+
+ def is_event_active(self, event: str, channel=Optional[str]):
+ return hasattr(self, event)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 7270d2b6d8..6d4abdb53a 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -26,7 +26,11 @@ from ...webhook.payloads import (
generate_translation_payload,
)
from ..base_plugin import BasePlugin
-from .tasks import trigger_webhook_sync, trigger_webhooks_for_event
+from .tasks import (
+ _get_webhooks_for_event,
+ trigger_webhook_sync,
+ trigger_webhooks_for_event,
+)
from .utils import (
from_payment_app_id,
parse_list_payment_gateways_response,
@@ -556,3 +560,8 @@ class WebhookPlugin(BasePlugin):
)
methods.extend(shipping_methods)
return methods
+
+ def is_event_active(self, event: str, channel=Optional[str]):
+ map_event = {"invoice_request": WebhookEventAsyncType.INVOICE_REQUESTED}
+ webhooks = _get_webhooks_for_event(event_type=map_event[event])
+ return any(webhooks)