Skip to content

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

Refactor invoices to their own module

Tomasz Szymanski15d0e7cbce8a
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index eec086d372..9ae14e6421 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -6,9 +6,10 @@ from .checkout.schema import CheckoutMutations, CheckoutQueries
from .core.schema import CoreMutations, CoreQueries
from .discount.schema import DiscountMutations, DiscountQueries
from .giftcard.schema import GiftCardMutations, GiftCardQueries
+from .invoice.schema import InvoiceMutations
from .menu.schema import MenuMutations, MenuQueries
from .meta.schema import MetaMutations
-from .order.schema import InvoiceMutations, OrderMutations, OrderQueries
+from .order.schema import OrderMutations, OrderQueries
from .page.schema import PageMutations, PageQueries
from .payment.schema import PaymentMutations, PaymentQueries
from .plugins.schema import PluginsMutations, PluginsQueries
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 58c3111e12..4763c9c325 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -8,6 +8,7 @@ from ...core.permissions import get_permissions_enum_list
from ...core.weight import WeightUnits
from ...discount import error_codes as discount_error_codes
from ...giftcard import error_codes as giftcard_error_codes
+from ...invoice import error_codes as invoice_error_codes
from ...menu import error_codes as menu_error_codes
from ...order import error_codes as order_error_codes
from ...page import error_codes as page_error_codes
@@ -92,7 +93,7 @@ GiftCardErrorCode = graphene.Enum.from_enum(giftcard_error_codes.GiftCardErrorCo
MenuErrorCode = graphene.Enum.from_enum(menu_error_codes.MenuErrorCode)
MetadataErrorCode = graphene.Enum.from_enum(core_error_codes.MetadataErrorCode)
OrderErrorCode = graphene.Enum.from_enum(order_error_codes.OrderErrorCode)
-InvoiceErrorCode = graphene.Enum.from_enum(order_error_codes.InvoiceErrorCode)
+InvoiceErrorCode = graphene.Enum.from_enum(invoice_error_codes.InvoiceErrorCode)
PageErrorCode = graphene.Enum.from_enum(page_error_codes.PageErrorCode)
PaymentErrorCode = graphene.Enum.from_enum(payment_error_codes.PaymentErrorCode)
PermissionGroupErrorCode = graphene.Enum.from_enum(
diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.py
index 1d351371b1..5f27c8e29b 100644
--- a/saleor/graphql/core/utils/error_codes.py
+++ b/saleor/graphql/core/utils/error_codes.py
@@ -6,8 +6,9 @@ from ....checkout.error_codes import CheckoutErrorCode
from ....core.error_codes import ShopErrorCode
from ....discount.error_codes import DiscountErrorCode
from ....giftcard.error_codes import GiftCardErrorCode
+from ....invoice.error_codes import InvoiceErrorCode
from ....menu.error_codes import MenuErrorCode
-from ....order.error_codes import InvoiceErrorCode, OrderErrorCode
+from ....order.error_codes import OrderErrorCode
from ....payment.error_codes import PaymentErrorCode
from ....plugins.error_codes import PluginErrorCode
from ....product.error_codes import ProductErrorCode
diff --git a/saleor/graphql/invoice/__init__.py b/saleor/graphql/invoice/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/invoice/enums.py b/saleor/graphql/invoice/enums.py
new file mode 100644
index 0000000000..4656fcaa06
--- /dev/null
+++ b/saleor/graphql/invoice/enums.py
@@ -0,0 +1,5 @@
+class InvoiceStatus:
+ PENDING = "pending"
+ PENDING_DELETE = "pending_delete"
+ DELETED = "deleted"
+ READY = "ready"
diff --git a/saleor/graphql/invoice/mutations.py b/saleor/graphql/invoice/mutations.py
new file mode 100644
index 0000000000..b6c91f1a86
--- /dev/null
+++ b/saleor/graphql/invoice/mutations.py
@@ -0,0 +1,268 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ...core.permissions import OrderPermissions
+from ...invoice import events, models
+from ...invoice.emails import send_invoice
+from ...invoice.error_codes import InvoiceErrorCode
+from ...order import OrderStatus
+from ..core.mutations import ModelDeleteMutation, ModelMutation
+from ..core.types.common import InvoiceError
+from ..invoice.enums import InvoiceStatus
+from ..invoice.types import Invoice
+from ..order.types import Order
+
+
+class RequestInvoice(ModelMutation):
+ class Meta:
+ description = "Request an invoice for the order."
+ model = models.Invoice
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = InvoiceError
+ error_type_field = "invoice_errors"
+
+ class Arguments:
+ order_id = graphene.ID(
+ required=True, description="ID of the order related to invoice."
+ )
+ number = graphene.String(
+ required=False, description="Invoice number (optional)."
+ )
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ if instance.status == OrderStatus.DRAFT:
+ raise ValidationError(
+ {
+ "orderId": ValidationError(
+ "Provided order status cannot be draft.",
+ code=InvoiceErrorCode.INVALID_STATUS,
+ )
+ }
+ )
+
+ if not instance.billing_address:
+ raise ValidationError(
+ {
+ "orderId": ValidationError(
+ "Billing address is not set on order.",
+ code=InvoiceErrorCode.NOT_READY,
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(
+ info, data["order_id"], only_type=Order, field="orderId"
+ )
+ cls.clean_instance(info, order)
+
+ invoice = models.Invoice.objects.create(
+ order=order, status=InvoiceStatus.PENDING, number=data.get("number")
+ )
+ 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")
+ )
+ invoice.refresh_from_db()
+ return RequestInvoice(invoice=invoice)
+
+
+class CreateInvoiceInput(graphene.InputObjectType):
+ number = graphene.String(required=True, description="Invoice number")
+ url = graphene.String(required=True, description="URL of an invoice to download.")
+
+
+class CreateInvoice(ModelMutation):
+ class Arguments:
+ order_id = graphene.ID(
+ required=True, description="ID of the order related to invoice."
+ )
+ input = CreateInvoiceInput(
+ required=True, description="Fields required when creating an invoice."
+ )
+
+ class Meta:
+ description = "Creates an invoice."
+ model = models.Invoice
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = InvoiceError
+ error_type_field = "invoice_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ validation_errors = {}
+ for field in ["url", "number"]:
+ if data["input"][field] == "":
+ validation_errors[field] = ValidationError(
+ f"{field} cannot be empty.", code=InvoiceErrorCode.REQUIRED,
+ )
+ if validation_errors:
+ raise ValidationError(validation_errors)
+ return data["input"]
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ if instance.status == OrderStatus.DRAFT:
+ raise ValidationError(
+ {
+ "orderId": ValidationError(
+ "Provided order status cannot be draft.",
+ code=InvoiceErrorCode.INVALID_STATUS,
+ )
+ }
+ )
+
+ if not instance.billing_address:
+ raise ValidationError(
+ {
+ "orderId": ValidationError(
+ "Billing address is not set on order.",
+ code=InvoiceErrorCode.NOT_READY,
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ instance = cls.get_node_or_error(
+ info, data["order_id"], only_type=Order, field="orderId"
+ )
+ cls.clean_instance(info, instance)
+ cleaned_input = cls.clean_input(info, instance, data)
+ invoice = cls.construct_instance(cls.get_instance(info, **data), cleaned_input)
+ invoice.order = instance
+ invoice.status = InvoiceStatus.READY
+ invoice.save()
+ events.invoice_created_event(
+ user=info.context.user,
+ invoice=invoice,
+ number=cleaned_input["number"],
+ url=cleaned_input["url"],
+ )
+ return CreateInvoice(invoice=invoice)
+
+
+class RequestDeleteInvoice(ModelMutation):
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of an invoice to request the deletion."
+ )
+
+ class Meta:
+ description = "Requests deletion of an invoice."
+ model = models.Invoice
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = InvoiceError
+ error_type_field = "invoice_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ invoice = cls.get_node_or_error(info, data["id"], only_type=Invoice)
+ 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()
+
+
+class DeleteInvoice(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of an invoice to delete.")
+
+ class Meta:
+ description = "Deletes an invoice."
+ model = models.Invoice
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = InvoiceError
+ error_type_field = "invoice_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ invoice_pk = 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")
+ url = graphene.String(description="URL of an invoice to download.")
+
+
+class UpdateInvoice(ModelMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of an invoice to update.")
+ input = UpdateInvoiceInput(
+ required=True, description="Fields to use when updating an invoice."
+ )
+
+ class Meta:
+ description = "Updates an invoice."
+ model = models.Invoice
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = InvoiceError
+ error_type_field = "invoice_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ number = instance.number or data["input"].get("number")
+ url = instance.url or data["input"].get("url")
+ if not number or not url:
+ raise ValidationError(
+ {
+ "invoice": ValidationError(
+ "URL and number need to be set after update operation.",
+ code=InvoiceErrorCode.URL_OR_NUMBER_NOT_SET,
+ )
+ }
+ )
+ return data["input"]
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ instance = cls.get_instance(info, **data)
+ cleaned_input = cls.clean_input(info, instance, data)
+ instance.update_invoice(
+ number=cleaned_input.get("number"), url=cleaned_input.get("url")
+ )
+ instance.status = InvoiceStatus.READY
+ instance.save()
+ return UpdateInvoice(invoice=instance)
+
+
+class SendInvoiceEmail(ModelMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of an invoice to be sent.")
+
+ class Meta:
+ description = "Send an invoice by email."
+ model = models.Invoice
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = InvoiceError
+ error_type_field = "invoice_errors"
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ error_code = None
+
+ if instance.status != InvoiceStatus.READY:
+ error_code = InvoiceErrorCode.NOT_READY
+ elif not instance.url or not instance.number:
+ error_code = InvoiceErrorCode.URL_OR_NUMBER_NOT_SET
+
+ if error_code:
+ raise ValidationError(
+ "Provided invoice is not ready to be sent.", code=error_code
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ 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/graphql/invoice/schema.py b/saleor/graphql/invoice/schema.py
new file mode 100644
index 0000000000..19cfe8976a
--- /dev/null
+++ b/saleor/graphql/invoice/schema.py
@@ -0,0 +1,19 @@
+import graphene
+
+from .mutations import (
+ CreateInvoice,
+ DeleteInvoice,
+ RequestDeleteInvoice,
+ RequestInvoice,
+ SendInvoiceEmail,
+ UpdateInvoice,
+)
+
+
+class InvoiceMutations(graphene.ObjectType):
+ request_invoice = RequestInvoice.Field()
+ request_delete_invoice = RequestDeleteInvoice.Field()
+ create_invoice = CreateInvoice.Field()
+ delete_invoice = DeleteInvoice.Field()
+ update_invoice = UpdateInvoice.Field()
+ send_invoice_email = SendInvoiceEmail.Field()
diff --git a/saleor/graphql/invoice/types.py b/saleor/graphql/invoice/types.py
new file mode 100644
index 0000000000..14867d0217
--- /dev/null
+++ b/saleor/graphql/invoice/types.py
@@ -0,0 +1,12 @@
+from graphene import relay
+
+from ...invoice import models
+from ..core.connection import CountableDjangoObjectType
+
+
+class Invoice(CountableDjangoObjectType):
+ class Meta:
+ description = "Represents an Invoice."
+ interfaces = [relay.Node]
+ model = models.Invoice
+ only_fields = ["id", "number", "url", "status"]
diff --git a/saleor/graphql/order/enums.py b/saleor/graphql/order/enums.py
index 637577290e..33df7d7efc 100644
--- a/saleor/graphql/order/enums.py
+++ b/saleor/graphql/order/enums.py
@@ -14,10 +14,3 @@ class OrderStatusFilter(graphene.Enum):
PARTIALLY_FULFILLED = "partially fulfilled"
FULFILLED = "fulfilled"
CANCELED = "canceled"
-
-
-class InvoiceStatus:
- PENDING = "pending"
- PENDING_DELETE = "pending_delete"
- DELETED = "deleted"
- READY = "ready"
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 97efa79d5d..88dd236544 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -4,7 +4,7 @@ from django.core.exceptions import ValidationError
from ....account.models import User
from ....core.permissions import OrderPermissions
from ....core.taxes import zero_taxed_money
-from ....order import OrderStatus, events, models
+from ....order import events, models
from ....order.actions import (
cancel_order,
clean_mark_order_as_paid,
@@ -14,19 +14,17 @@ from ....order.actions import (
order_shipping_updated,
order_voided,
)
-from ....order.emails import send_invoice
-from ....order.error_codes import InvoiceErrorCode, OrderErrorCode
+from ....order.error_codes import OrderErrorCode
from ....order.utils import get_valid_shipping_methods_for_order
from ....payment import CustomPaymentChoices, PaymentError, gateway
from ...account.types import AddressInput
-from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ...core.mutations import BaseMutation
from ...core.scalars import Decimal
-from ...core.types.common import InvoiceError, OrderError
+from ...core.types.common import OrderError
from ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutation
from ...meta.deprecated.types import MetaInput, MetaPath
-from ...order.enums import InvoiceStatus
from ...order.mutations.draft_orders import DraftOrderUpdate
-from ...order.types import Invoice, Order, OrderEvent
+from ...order.types import Order, OrderEvent
from ...shipping.types import ShippingMethod
from ...utils import get_user_or_app_from_context
@@ -515,258 +513,3 @@ class OrderClearPrivateMeta(ClearMetaBaseMutation):
model = models.Order
permissions = (OrderPermissions.MANAGE_ORDERS,)
public = False
-
-
-class RequestInvoice(ModelMutation):
- class Meta:
- description = "Request an invoice for the order."
- model = models.Invoice
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = InvoiceError
- error_type_field = "invoice_errors"
-
- class Arguments:
- order_id = graphene.ID(
- required=True, description="ID of the order related to invoice."
- )
- number = graphene.String(
- required=False, description="Invoice number (optional)."
- )
-
- @classmethod
- def clean_instance(cls, info, instance):
- if instance.status == OrderStatus.DRAFT:
- raise ValidationError(
- {
- "orderId": ValidationError(
- "Provided order status cannot be draft.",
- code=InvoiceErrorCode.INVALID_STATUS,
- )
- }
- )
-
- if not instance.billing_address:
- raise ValidationError(
- {
- "orderId": ValidationError(
- "Billing address is not set on order.",
- code=InvoiceErrorCode.NOT_READY,
- )
- }
- )
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(
- info, data["order_id"], only_type=Order, field="orderId"
- )
- cls.clean_instance(info, order)
-
- invoice = models.Invoice.objects.create(
- order=order, status=InvoiceStatus.PENDING, number=data.get("number")
- )
- 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")
- )
- invoice.refresh_from_db()
- return RequestInvoice(invoice=invoice)
-
-
-class CreateInvoiceInput(graphene.InputObjectType):
- number = graphene.String(required=True, description="Invoice number")
- url = graphene.String(required=True, description="URL of an invoice to download.")
-
-
-class CreateInvoice(ModelMutation):
- class Arguments:
- order_id = graphene.ID(
- required=True, description="ID of the order related to invoice."
- )
- input = CreateInvoiceInput(
- required=True, description="Fields required when creating an invoice."
- )
-
- class Meta:
- description = "Creates an invoice."
- model = models.Invoice
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = InvoiceError
- error_type_field = "invoice_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- validation_errors = {}
- for field in ["url", "number"]:
- if data["input"][field] == "":
- validation_errors[field] = ValidationError(
- f"{field} cannot be empty.", code=InvoiceErrorCode.REQUIRED,
- )
- if validation_errors:
- raise ValidationError(validation_errors)
- return data["input"]
-
- @classmethod
- def clean_instance(cls, info, instance):
- if instance.status == OrderStatus.DRAFT:
- raise ValidationError(
- {
- "orderId": ValidationError(
- "Provided order status cannot be draft.",
- code=InvoiceErrorCode.INVALID_STATUS,
- )
- }
- )
-
- if not instance.billing_address:
- raise ValidationError(
- {
- "orderId": ValidationError(
- "Billing address is not set on order.",
- code=InvoiceErrorCode.NOT_READY,
- )
- }
- )
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- instance = cls.get_node_or_error(
- info, data["order_id"], only_type=Order, field="orderId"
- )
- cls.clean_instance(info, instance)
- cleaned_input = cls.clean_input(info, instance, data)
- invoice = cls.construct_instance(cls.get_instance(info, **data), cleaned_input)
- invoice.order = instance
- invoice.status = InvoiceStatus.READY
- invoice.save()
- events.invoice_created_event(
- user=info.context.user,
- invoice=invoice,
- number=cleaned_input["number"],
- url=cleaned_input["url"],
- )
- return CreateInvoice(invoice=invoice)
-
-
-class RequestDeleteInvoice(ModelMutation):
- class Arguments:
- id = graphene.ID(
- required=True, description="ID of an invoice to request the deletion."
- )
-
- class Meta:
- description = "Requests deletion of an invoice."
- model = models.Invoice
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = InvoiceError
- error_type_field = "invoice_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- invoice = cls.get_node_or_error(info, data["id"], only_type=Invoice)
- 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()
-
-
-class DeleteInvoice(ModelDeleteMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of an invoice to delete.")
-
- class Meta:
- description = "Deletes an invoice."
- model = models.Invoice
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = InvoiceError
- error_type_field = "invoice_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- invoice_pk = 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")
- url = graphene.String(description="URL of an invoice to download.")
-
-
-class UpdateInvoice(ModelMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of an invoice to update.")
- input = UpdateInvoiceInput(
- required=True, description="Fields to use when updating an invoice."
- )
-
- class Meta:
- description = "Updates an invoice."
- model = models.Invoice
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = InvoiceError
- error_type_field = "invoice_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- number = instance.number or data["input"].get("number")
- url = instance.url or data["input"].get("url")
- if not number or not url:
- raise ValidationError(
- {
- "invoice": ValidationError(
- "URL and number need to be set after update operation.",
- code=InvoiceErrorCode.URL_OR_NUMBER_NOT_SET,
- )
- }
- )
- return data["input"]
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- instance = cls.get_instance(info, **data)
- cleaned_input = cls.clean_input(info, instance, data)
- instance.update_invoice(
- number=cleaned_input.get("number"), url=cleaned_input.get("url")
- )
- instance.status = InvoiceStatus.READY
- instance.save()
- return UpdateInvoice(invoice=instance)
-
-
-class SendInvoiceEmail(ModelMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of an invoice to be sent.")
-
- class Meta:
- description = "Send an invoice by email."
- model = models.Invoice
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = InvoiceError
- error_type_field = "invoice_errors"
-
- @classmethod
- def clean_instance(cls, info, instance):
- error_code = None
-
- if instance.status != InvoiceStatus.READY:
- error_code = InvoiceErrorCode.NOT_READY
- elif not instance.url or not instance.number:
- error_code = InvoiceErrorCode.URL_OR_NUMBER_NOT_SET
-
- if error_code:
- raise ValidationError(
- "Provided invoice is not ready to be sent.", code=error_code
- )
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- 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/graphql/order/schema.py b/saleor/graphql/order/schema.py
index ab94e8f052..3abce46c9c 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -28,8 +28,6 @@ from .mutations.fulfillments import (
OrderFulfill,
)
from .mutations.orders import (
- CreateInvoice,
- DeleteInvoice,
OrderAddNote,
OrderCancel,
OrderCapture,
@@ -42,10 +40,6 @@ from .mutations.orders import (
OrderUpdatePrivateMeta,
OrderUpdateShipping,
OrderVoid,
- RequestDeleteInvoice,
- RequestInvoice,
- SendInvoiceEmail,
- UpdateInvoice,
)
from .resolvers import (
resolve_draft_orders,
@@ -224,12 +218,3 @@ class OrderMutations(graphene.ObjectType):
order_void = OrderVoid.Field()
order_bulk_cancel = OrderBulkCancel.Field()
-
-
-class InvoiceMutations(graphene.ObjectType):
- request_invoice = RequestInvoice.Field()
- request_delete_invoice = RequestDeleteInvoice.Field()
- create_invoice = CreateInvoice.Field()
- delete_invoice = DeleteInvoice.Field()
- update_invoice = UpdateInvoice.Field()
- send_invoice_email = SendInvoiceEmail.Field()
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 4363e1d5f5..ae0e46f898 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -17,6 +17,7 @@ from ..core.types.common import Image
from ..core.types.money import Money, TaxedMoney
from ..decorators import permission_required
from ..giftcard.types import GiftCard
+from ..invoice.types import Invoice
from ..meta.deprecated.resolvers import resolve_meta, resolve_private_meta
from ..meta.types import ObjectWithMetadata
from ..payment.types import OrderAction, Payment, PaymentChargeStatusEnum
@@ -284,14 +285,6 @@ class OrderLine(CountableDjangoObjectType):
return root.translated_variant_name
-class Invoice(CountableDjangoObjectType):
- class Meta:
- description = "Represents an Invoice."
- interfaces = [relay.Node]
- model = models.Invoice
- only_fields = ["id", "number", "url", "status"]
-
-
class Order(CountableDjangoObjectType):
fulfillments = graphene.List(
Fulfillment, required=True, description="List of shipments for the order."
diff --git a/saleor/invoice/__init__.py b/saleor/invoice/__init__.py
new file mode 100644
index 0000000000..76ff9dfba1
--- /dev/null
+++ b/saleor/invoice/__init__.py
@@ -0,0 +1,14 @@
+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/invoice/emails.py b/saleor/invoice/emails.py
new file mode 100644
index 0000000000..c5fe2c86f8
--- /dev/null
+++ b/saleor/invoice/emails.py
@@ -0,0 +1,29 @@
+from templated_email import send_templated_mail
+
+from ..celeryconf import app
+from ..core.emails import get_email_context
+from .models import Invoice
+
+
+def collect_invoice_data_for_email(invoice_pk, template):
+ """Collect the required data for sending emails."""
+ invoice = Invoice.objects.get(pk=invoice_pk)
+ recipient_email = invoice.order.user.email
+ send_kwargs, email_context = get_email_context()
+
+ email_context["number"] = invoice.number
+ email_context["download_url"] = invoice.url
+
+ return {
+ "recipient_list": [recipient_email],
+ "template_name": template,
+ "context": email_context,
+ **send_kwargs,
+ }
+
+
+def send_invoice(invoice_pk):
+ """Send an invoice to user of related order with URL to download it."""
+ email_data = collect_invoice_data_for_email(invoice_pk, "order/send_invoice")
+ send_templated_mail(**email_data)
diff --git a/saleor/invoice/error_codes.py b/saleor/invoice/error_codes.py
new file mode 100644
index 0000000000..7497bd0cc7
--- /dev/null
+++ b/saleor/invoice/error_codes.py
@@ -0,0 +1,9 @@
+from enum import Enum
+
+
+class InvoiceErrorCode(Enum):
+ REQUIRED = "required"
+ NOT_READY = "not_ready"
+ URL_OR_NUMBER_NOT_SET = "url_or_number_not_set"
+ NOT_FOUND = "not_found"
+ INVALID_STATUS = "invalid_status"
diff --git a/saleor/invoice/events.py b/saleor/invoice/events.py
new file mode 100644
index 0000000000..a8116f5ddc
--- /dev/null
+++ b/saleor/invoice/events.py
@@ -0,0 +1,68 @@
+from typing import Optional
+
+from ..account.models import User
+from ..order.models import Order
+from .models import Invoice, InvoiceEvent, InvoiceEvents
+
+UserType = Optional[User]
+
+
+def _user_is_valid(user: UserType) -> bool:
+ return bool(user and not user.is_anonymous)
+
+
+def invoice_requested_event(
+ *, user: UserType, order: Order, number: str
+) -> InvoiceEvent:
+ if not _user_is_valid(user):
+ user = None
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.REQUESTED,
+ user=user,
+ order=order,
+ parameters={"number": number},
+ )
+
+
+def invoice_requested_deletion(*, user: UserType, invoice: Invoice) -> InvoiceEvent:
+ if not _user_is_valid(user):
+ user = None
+ 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:
+ if not _user_is_valid(user):
+ user = None
+ 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:
+ if not _user_is_valid(user):
+ user = None
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.DELETED, user=user, parameters={"invoice_id": invoice_id}
+ )
+
+
+def invoice_sent_event(*, user: UserType, invoice: Invoice) -> InvoiceEvent:
+ if not _user_is_valid(user):
+ user = None
+ return InvoiceEvent.objects.create(
+ type=InvoiceEvents.SENT,
+ user=user,
+ invoice=invoice,
+ parameters={"email": invoice.order.user.email}, # type: ignore
+ )
diff --git a/saleor/order/migrations/0085_invoiceevent.py b/saleor/invoice/migrations/0001_initial.py
similarity index 60%
rename from saleor/order/migrations/0085_invoiceevent.py
rename to saleor/invoice/migrations/0001_initial.py
index 0112e76115..e22b7b24b4 100644
--- a/saleor/order/migrations/0085_invoiceevent.py
+++ b/saleor/invoice/migrations/0001_initial.py
@@ -1,4 +1,4 @@
-# Generated by Django 3.0.6 on 2020-05-16 13:17
+# Generated by Django 3.0.6 on 2020-05-25 09:33
import django.contrib.postgres.fields.jsonb
import django.db.models.deletion
@@ -11,12 +11,60 @@ import saleor.core.utils.json_serializer
class Migration(migrations.Migration):
+ initial = True
+
dependencies = [
+ ("order", "0085_delete_invoice"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
- ("order", "0084_auto_20200426_0647"),
]
operations = [
+ migrations.CreateModel(
+ name="Invoice",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "private_metadata",
+ django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ (
+ "metadata",
+ django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ ("number", models.CharField(max_length=255, null=True)),
+ ("created", models.DateTimeField(null=True)),
+ ("url", models.URLField(max_length=2048, null=True)),
+ ("status", models.CharField(default="pending", max_length=32)),
+ (
+ "order",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="invoices",
+ to="order.Order",
+ ),
+ ),
+ ],
+ options={"abstract": False,}, # noqa: E231
+ ),
migrations.CreateModel(
name="InvoiceEvent",
fields=[
@@ -66,7 +114,7 @@ class Migration(migrations.Migration):
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="events",
- to="order.Invoice",
+ to="invoice.Invoice",
),
),
(
@@ -89,7 +137,6 @@ class Migration(migrations.Migration):
),
),
],
- # flake8: noqa
- options={"ordering": ("date",),},
+ options={"ordering": ("date",),}, # noqa: E231
),
]
diff --git a/saleor/invoice/migrations/__init__.py b/saleor/invoice/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/invoice/models.py b/saleor/invoice/models.py
new file mode 100644
index 0000000000..1d4f6150e3
--- /dev/null
+++ b/saleor/invoice/models.py
@@ -0,0 +1,67 @@
+from django.conf import settings
+from django.contrib.postgres.fields import JSONField
+from django.db import models
+from django.utils.timezone import now
+
+from ..core.models import ModelWithMetadata
+from ..core.utils.json_serializer import CustomJsonEncoder
+from ..graphql.invoice.enums import InvoiceStatus
+from ..order.models import Order
+from . import InvoiceEvents
+
+
+class InvoiceQueryset(models.QuerySet):
+ def ready(self):
+ return self.filter(status=InvoiceStatus.READY)
+
+
+class Invoice(ModelWithMetadata):
+ order = models.ForeignKey(
+ Order, related_name="invoices", null=True, on_delete=models.SET_NULL
+ )
+ number = models.CharField(max_length=255, null=True)
+ created = models.DateTimeField(null=True)
+ url = models.URLField(null=True, max_length=2048)
+ status = models.CharField(max_length=32, default=InvoiceStatus.PENDING)
+ objects = InvoiceQueryset.as_manager()
+
+ def update_invoice(self, number=None, url=None):
+ if number is not None:
+ self.number = number
+ if url is not None:
+ self.url = url
+ self.save()
+
+ def fullfill_invoice(self):
+ self.status = InvoiceStatus.READY
+ 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/saleor/order/__init__.py b/saleor/order/__init__.py
index 4bbaeee712..30b7055ae2 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -103,19 +103,3 @@ 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/emails.py b/saleor/order/emails.py
index 4cc8c704e3..95104b4aa0 100644
--- a/saleor/order/emails.py
+++ b/saleor/order/emails.py
@@ -7,7 +7,7 @@ from ..celeryconf import app
from ..core.emails import get_email_context, prepare_url
from ..seo.schema.email import get_order_confirmation_markup
from . import events
-from .models import Fulfillment, Invoice, Order
+from .models import Fulfillment, Order
CONFIRM_ORDER_TEMPLATE = "order/confirm_order"
STAFF_CONFIRM_ORDER_TEMPLATE = "order/staff_confirm_order"
@@ -101,30 +101,6 @@ def send_staff_order_confirmation(order_pk, redirect_url):
send_templated_mail(**staff_email_data)
-def collect_invoice_data_for_email(invoice_pk, template):
- """Collect the required data for sending emails."""
- invoice = Invoice.objects.get(pk=invoice_pk)
- recipient_email = invoice.order.user.email
- send_kwargs, email_context = get_email_context()
-
- email_context["number"] = invoice.number
- email_context["download_url"] = invoice.url
-
- return {
- "recipient_list": [recipient_email],
- "template_name": template,
- "context": email_context,
- **send_kwargs,
- }
-
-
-def send_invoice(invoice_pk):
- """Send an invoice to user of related order with URL to download it."""
- email_data = collect_invoice_data_for_email(invoice_pk, "order/send_invoice")
- send_templated_mail(**email_data)
-
-
@app.task
def send_fulfillment_confirmation(order_pk, fulfillment_pk):
email_data = collect_data_for_fullfillment_email(
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 2efa43e469..e16f113cc9 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -24,11 +24,3 @@ class OrderErrorCode(Enum):
ZERO_QUANTITY = "zero_quantity"
INSUFFICIENT_STOCK = "insufficient_stock"
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
-
-
-class InvoiceErrorCode(Enum):
- REQUIRED = "required"
- NOT_READY = "not_ready"
- URL_OR_NUMBER_NOT_SET = "url_or_number_not_set"
- NOT_FOUND = "not_found"
- INVALID_STATUS = "invalid_status"
diff --git a/saleor/order/events.py b/saleor/order/events.py
index 0bab7f2b6c..b8194577ea 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, Invoice, Order, OrderLine
+from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
from ..payment.models import Payment
from . import OrderEvents, OrderEventsEmails
-from .models import InvoiceEvent, InvoiceEvents, OrderEvent
+from .models import OrderEvent
UserType = Optional[User]
@@ -95,63 +95,6 @@ def draft_order_removed_products_event(
)
-def invoice_requested_event(
- *, user: UserType, order: Order, number: str
-) -> InvoiceEvent:
- if not _user_is_valid(user):
- user = None
- return InvoiceEvent.objects.create(
- type=InvoiceEvents.REQUESTED,
- user=user,
- order=order,
- parameters={"number": number},
- )
-
-
-def invoice_requested_deletion(*, user: UserType, invoice: Invoice) -> InvoiceEvent:
- if not _user_is_valid(user):
- user = None
- 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:
- if not _user_is_valid(user):
- user = None
- 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:
- if not _user_is_valid(user):
- user = None
- return InvoiceEvent.objects.create(
- type=InvoiceEvents.DELETED, user=user, parameters={"invoice_id": invoice_id}
- )
-
-
-def invoice_sent_event(*, user: UserType, invoice: Invoice) -> InvoiceEvent:
- if not _user_is_valid(user):
- user = None
- 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_delete_invoice.py b/saleor/order/migrations/0085_delete_invoice.py
new file mode 100644
index 0000000000..c9369bbeef
--- /dev/null
+++ b/saleor/order/migrations/0085_delete_invoice.py
@@ -0,0 +1,14 @@
+# Generated by Django 3.0.6 on 2020-05-25 09:33
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0084_auto_20200426_0647"),
+ ]
+
+ operations = [
+ migrations.DeleteModel(name="Invoice",),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 2a92915d80..ceae581fdd 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -22,10 +22,9 @@ from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.weight import WeightUnits, zero_weight
from ..discount.models import Voucher
from ..giftcard.models import GiftCard
-from ..graphql.order.enums import InvoiceStatus
from ..payment import ChargeStatus, TransactionKind
from ..shipping.models import ShippingMethod
-from . import FulfillmentStatus, InvoiceEvents, OrderEvents, OrderStatus
+from . import FulfillmentStatus, OrderEvents, OrderStatus
class OrderQueryset(models.QuerySet):
@@ -508,60 +507,3 @@ class OrderEvent(models.Model):
def __repr__(self):
return f"{self.__class__.__name__}(type={self.type!r}, user={self.user!r})"
-
-
-class InvoiceQueryset(models.QuerySet):
- def ready(self):
- return self.filter(status=InvoiceStatus.READY)
-
-
-class Invoice(ModelWithMetadata):
- order = models.ForeignKey(
- Order, related_name="invoices", null=True, on_delete=models.SET_NULL
- )
- number = models.CharField(max_length=255, null=True)
- created = models.DateTimeField(null=True)
- url = models.URLField(null=True, max_length=2048)
- status = models.CharField(max_length=32, default=InvoiceStatus.PENDING)
- objects = InvoiceQueryset.as_manager()
-
- def update_invoice(self, number=None, url=None):
- if number is not None:
- self.number = number
- if url is not None:
- self.url = url
- self.save()
-
- def fullfill_invoice(self):
- self.status = InvoiceStatus.READY
- 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/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 5bb81b3adb..57843d54d9 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -14,7 +14,8 @@ if TYPE_CHECKING:
from ..discount import DiscountInfo
from ..product.models import Product, ProductType
from ..account.models import Address, User
- from ..order.models import Fulfillment, Invoice, OrderLine, Order
+ from ..order.models import Fulfillment, OrderLine, Order
+ from ..invoice.models import Invoice
from ..payment.interface import GatewayResponse, PaymentData, CustomerSource
diff --git a/saleor/plugins/invoicing/__init__.py b/saleor/plugins/invoicing/__init__.py
index d7346e7eee..0b1270bfb8 100644
--- a/saleor/plugins/invoicing/__init__.py
+++ b/saleor/plugins/invoicing/__init__.py
@@ -11,7 +11,7 @@ from django.core.files.storage import default_storage
from django.template.loader import get_template
from weasyprint import HTML
-from ...order.models import Invoice
+from ...invoice.models import Invoice
def make_full_invoice_number(number=1):
diff --git a/saleor/plugins/invoicing/plugin.py b/saleor/plugins/invoicing/plugin.py
index cb172a9d82..9bfa478a20 100644
--- a/saleor/plugins/invoicing/plugin.py
+++ b/saleor/plugins/invoicing/plugin.py
@@ -3,7 +3,8 @@ from typing import Any, Optional
from django.urls import reverse
from ...core.utils import build_absolute_uri
-from ...order.models import Invoice, Order
+from ...invoice.models import Invoice
+from ...order.models import Order
from ..base_plugin import BasePlugin
from . import generate_invoice_number, generate_invoice_pdf
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 7d0c31b953..ef1b40894f 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -20,7 +20,8 @@ if TYPE_CHECKING:
from ..checkout.models import Checkout, CheckoutLine
from ..product.models import Product, ProductType
from ..account.models import Address, User
- from ..order.models import Fulfillment, Invoice, OrderLine, Order
+ from ..order.models import Fulfillment, OrderLine, Order
+ from ..invoice.models import Invoice
from ..payment.interface import (
PaymentData,
TokenConfig,
diff --git a/saleor/settings.py b/saleor/settings.py
index 2a5e6303d9..32eb58d13d 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -233,6 +233,7 @@ INSTALLED_APPS = [
"saleor.graphql",
"saleor.menu",
"saleor.order",
+ "saleor.invoice",
"saleor.seo",
"saleor.shipping",
"saleor.search",
diff --git a/tests/api/test_invoice.py b/tests/api/test_invoice.py
new file mode 100644
index 0000000000..818d7b7ce7
--- /dev/null
+++ b/tests/api/test_invoice.py
@@ -0,0 +1,524 @@
+import uuid
+from unittest.mock import Mock, patch
+
+import graphene
+
+from saleor.graphql.invoice.enums import InvoiceStatus
+from saleor.invoice.error_codes import InvoiceErrorCode
+from saleor.invoice.models import Invoice, InvoiceEvent, InvoiceEvents
+from saleor.order import OrderStatus
+
+from .utils import assert_no_permission, get_graphql_content
+
+REQUEST_INVOICE_MUTATION = """
+ mutation RequestInvoice($orderId: ID!, $number: String) {
+ requestInvoice(
+ orderId: $orderId,
+ number: $number
+ ) {
+ invoiceErrors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+CREATE_INVOICE_MUTATION = """
+ mutation CreateInvoice($orderId: ID!, $number: String!, $url: String!) {
+ createInvoice(
+ orderId: $orderId,
+ input: {
+ number: $number,
+ url: $url
+ }
+ ) {
+ invoice {
+ number
+ url
+ }
+ invoiceErrors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+REQUEST_DELETE_INVOICE_MUTATION = """
+ mutation RequestDeleteInvoice($id: ID!) {
+ requestDeleteInvoice(
+ id: $id
+ ) {
+ invoiceErrors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+DELETE_INVOICE_MUTATION = """
+ mutation DeleteInvoice($id: ID!) {
+ deleteInvoice(
+ id: $id
+ ) {
+ invoiceErrors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+UPDATE_INVOICE_MUTATION = """
+ mutation UpdateInvoice($id: ID!, $number: String, $url: String) {
+ updateInvoice(
+ id: $id,
+ input: {
+ number: $number,
+ url: $url
+ }
+ ) {
+ invoice {
+ number
+ url
+ }
+ invoiceErrors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+SEND_INVOICE_MUTATION = """
+ mutation SendInvoice($id: ID!) {
+ sendInvoiceEmail(
+ id: $id
+ ) {
+ invoiceErrors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+@patch("saleor.plugins.base_plugin.BasePlugin.invoice_request")
+def test_request_invoice(
+ plugin_mock, staff_api_client, permission_manage_orders, order
+):
+ number = "01/12/2020/TEST"
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": number,
+ }
+ staff_api_client.post_graphql(
+ REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ 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()
+
+
+@patch("saleor.plugins.invoicing.default_storage")
+def test_request_invoice_with_plugin(
+ stor_mock, staff_api_client, permission_manage_orders, order, setup_invoicing
+):
+ stor_mock.save = Mock(return_value=f"{uuid.uuid4()}.pdf")
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ }
+ staff_api_client.post_graphql(
+ REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ invoice = Invoice.objects.get(order=order)
+ assert invoice.status == InvoiceStatus.READY
+
+
+def test_request_invoice_draft_order(staff_api_client, permission_manage_orders, order):
+ order.status = OrderStatus.DRAFT
+ order.save()
+ number = "01/12/2020/TEST"
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": number,
+ }
+ response = staff_api_client.post_graphql(
+ REQUEST_INVOICE_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"]["requestInvoice"]["invoiceErrors"][0]
+ assert error["field"] == "orderId"
+ assert error["code"] == InvoiceErrorCode.INVALID_STATUS.name
+
+
+def test_request_invoice_no_billing_address(
+ staff_api_client, permission_manage_orders, order
+):
+ order.billing_address = None
+ order.save()
+ number = "01/12/2020/TEST"
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": number,
+ }
+ response = staff_api_client.post_graphql(
+ REQUEST_INVOICE_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"]["requestInvoice"]["invoiceErrors"][0]
+ assert error["field"] == "orderId"
+ assert error["code"] == InvoiceErrorCode.NOT_READY.name
+
+
+def test_request_invoice_no_number(staff_api_client, permission_manage_orders, order):
+ variables = {"orderId": graphene.Node.to_global_id("Order", order.pk)}
+ staff_api_client.post_graphql(
+ REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ invoice = Invoice.objects.get(order=order.pk)
+ assert invoice.number is None
+
+
+def test_request_invoice_invalid_order(staff_api_client, permission_manage_orders):
+ variables = {"orderId": "T3JkZXI6MTMzNzEzMzc=", "number": "01/12/2020/TEST"}
+ response = staff_api_client.post_graphql(
+ REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["requestInvoice"]["invoiceErrors"][0]
+ assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
+ assert error["field"] == "orderId"
+
+
+@patch("saleor.plugins.base_plugin.BasePlugin.invoice_delete")
+def test_request_delete_invoice(
+ plugin_mock, staff_api_client, permission_manage_orders, order
+):
+ invoice = Invoice.objects.create(order=order)
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.post_graphql(REQUEST_DELETE_INVOICE_MUTATION, variables)
+ 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")
+def test_request_delete_invoice_invalid_id(
+ plugin_mock, staff_api_client, permission_manage_orders
+):
+ variables = {"id": graphene.Node.to_global_id("Invoice", 1337)}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(REQUEST_DELETE_INVOICE_MUTATION, variables)
+ content = get_graphql_content(response)
+ error = content["data"]["requestDeleteInvoice"]["invoiceErrors"][0]
+ assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
+ assert error["field"] == "id"
+ plugin_mock.assert_not_called()
+
+
+@patch("saleor.plugins.base_plugin.BasePlugin.invoice_delete")
+def test_request_delete_invoice_no_permission(
+ plugin_mock, staff_api_client, permission_manage_orders, order
+):
+ invoice = Invoice.objects.create(order=order)
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+ response = staff_api_client.post_graphql(REQUEST_DELETE_INVOICE_MUTATION, variables)
+ assert_no_permission(response)
+ plugin_mock.assert_not_called()
+
+
+def test_delete_invoice(staff_api_client, permission_manage_orders, order):
+ invoice = Invoice.objects.create(order=order)
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+ response = staff_api_client.post_graphql(
+ DELETE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ 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")
+def test_delete_invoice_invalid_id(
+ plugin_mock, staff_api_client, permission_manage_orders
+):
+ variables = {"id": graphene.Node.to_global_id("Invoice", 1337)}
+ response = staff_api_client.post_graphql(
+ DELETE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["deleteInvoice"]["invoiceErrors"][0]
+ assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
+ assert error["field"] == "id"
+ plugin_mock.assert_not_called()
+
+
+def test_update_invoice(staff_api_client, permission_manage_orders, order):
+ invoice = Invoice.objects.create(order=order)
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ variables = {
+ "id": graphene.Node.to_global_id("Invoice", invoice.pk),
+ "number": number,
+ "url": url,
+ }
+ response = staff_api_client.post_graphql(
+ UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ invoice.refresh_from_db()
+ assert invoice.status == InvoiceStatus.READY
+ assert invoice.number == content["data"]["updateInvoice"]["invoice"]["number"]
+ assert invoice.url == content["data"]["updateInvoice"]["invoice"]["url"]
+
+
+def test_update_invoice_single_value(staff_api_client, permission_manage_orders, order):
+ number = "01/12/2020/TEST"
+ invoice = Invoice.objects.create(order=order, number=number)
+ url = "http://www.example.com"
+ variables = {
+ "id": graphene.Node.to_global_id("Invoice", invoice.pk),
+ "url": url,
+ }
+ response = staff_api_client.post_graphql(
+ UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ invoice.refresh_from_db()
+ assert invoice.status == InvoiceStatus.READY
+ assert invoice.number == number
+ assert invoice.url == content["data"]["updateInvoice"]["invoice"]["url"]
+
+
+def test_update_invoice_missing_number(
+ staff_api_client, permission_manage_orders, order
+):
+ invoice = Invoice.objects.create(order=order)
+ url = "http://www.example.com"
+ variables = {
+ "id": graphene.Node.to_global_id("Invoice", invoice.pk),
+ "url": url,
+ }
+ response = staff_api_client.post_graphql(
+ UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ invoice.refresh_from_db()
+ error = content["data"]["updateInvoice"]["invoiceErrors"][0]
+ assert error["code"] == InvoiceErrorCode.URL_OR_NUMBER_NOT_SET.name
+ assert error["field"] == "invoice"
+ assert invoice.url is None
+ assert invoice.status == InvoiceStatus.PENDING
+
+
+def test_update_invoice_invalid_id(staff_api_client, permission_manage_orders):
+ variables = {"id": "SW52b2ljZToxMzM3", "number": "01/12/2020/TEST"}
+ response = staff_api_client.post_graphql(
+ UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["updateInvoice"]["invoiceErrors"][0]
+ assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
+ assert error["field"] == "id"
+
+
+def test_create_invoice(staff_api_client, permission_manage_orders, order):
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": number,
+ "url": url,
+ }
+ response = staff_api_client.post_graphql(
+ CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ invoice = Invoice.objects.get(order_id=order.pk, url=url, number=number)
+ 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_no_billing_address(
+ staff_api_client, permission_manage_orders, order
+):
+ order.billing_address = None
+ order.save()
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": number,
+ "url": url,
+ }
+ response = staff_api_client.post_graphql(
+ CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not Invoice.objects.filter(
+ order_id=order.pk, url=url, number=number
+ ).exists()
+ error = content["data"]["createInvoice"]["invoiceErrors"][0]
+ assert error["field"] == "orderId"
+ assert error["code"] == InvoiceErrorCode.NOT_READY.name
+
+
+def test_create_invoice_for_draft_order(
+ staff_api_client, permission_manage_orders, order
+):
+ order.status = OrderStatus.DRAFT
+ order.save()
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": number,
+ "url": url,
+ }
+ response = staff_api_client.post_graphql(
+ CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not Invoice.objects.filter(
+ order_id=order.pk, url=url, number=number
+ ).exists()
+ error = content["data"]["createInvoice"]["invoiceErrors"][0]
+ assert error["field"] == "orderId"
+ assert error["code"] == InvoiceErrorCode.INVALID_STATUS.name
+
+
+def test_create_invoice_invalid_id(staff_api_client, permission_manage_orders):
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", 1337),
+ "number": "01/12/2020/TEST",
+ "url": "http://www.example.com",
+ }
+ response = staff_api_client.post_graphql(
+ CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["createInvoice"]["invoiceErrors"][0]
+ assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
+ assert error["field"] == "orderId"
+
+
+def test_create_invoice_empty_params(staff_api_client, permission_manage_orders, order):
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "number": "",
+ "url": "",
+ }
+ response = staff_api_client.post_graphql(
+ CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ errors = content["data"]["createInvoice"]["invoiceErrors"]
+ assert errors[0] == {
+ "field": "url",
+ "code": InvoiceErrorCode.REQUIRED.name,
+ }
+ assert errors[1] == {
+ "field": "number",
+ "code": InvoiceErrorCode.REQUIRED.name,
+ }
+
+ assert not Invoice.objects.filter(
+ order_id=order.pk, status=InvoiceStatus.READY
+ ).exists()
+
+
+@patch("saleor.invoice.emails.send_invoice.delay")
+def test_send_invoice(email_mock, staff_api_client, permission_manage_orders, order):
+ number = "01/12/2020/TEST"
+ url = "http://www.example.com"
+ invoice = Invoice.objects.create(
+ order=order, number=number, url=url, status=InvoiceStatus.READY
+ )
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+ response = staff_api_client.post_graphql(
+ SEND_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ 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.invoice.emails.send_invoice.delay")
+def test_send_pending_invoice(
+ email_mock, staff_api_client, permission_manage_orders, order
+):
+ invoice = Invoice.objects.create(
+ order=order, number=None, url=None, status=InvoiceStatus.PENDING
+ )
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+ response = staff_api_client.post_graphql(
+ SEND_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ errors = content["data"]["sendInvoiceEmail"]["invoiceErrors"]
+ assert errors == [{"field": None, "code": InvoiceErrorCode.NOT_READY.name}]
+ email_mock.assert_not_called()
+
+
+@patch("saleor.invoice.emails.send_invoice.delay")
+def test_send_not_ready_invoice(
+ email_mock, staff_api_client, permission_manage_orders, order
+):
+ invoice = Invoice.objects.create(
+ order=order, number=None, url=None, status=InvoiceStatus.READY
+ )
+ variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
+ response = staff_api_client.post_graphql(
+ SEND_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ errors = content["data"]["sendInvoiceEmail"]["invoiceErrors"]
+ [{"field": None, "code": "URL_OR_NUMBER_NOT_SET"}]
+ assert errors == [
+ {"field": None, "code": InvoiceErrorCode.URL_OR_NUMBER_NOT_SET.name}
+ ]
+ email_mock.assert_not_called()
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index 4787369bdb..ba0b8fb1fd 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -12,7 +12,6 @@ from saleor.account.models import CustomerEvent
from saleor.core.permissions import OrderPermissions
from saleor.core.taxes import zero_taxed_money
from saleor.graphql.core.enums import ReportingPeriod
-from saleor.graphql.order.enums import InvoiceStatus
from saleor.graphql.order.mutations.orders import (
clean_order_cancel,
clean_order_capture,
@@ -22,8 +21,8 @@ from saleor.graphql.order.mutations.orders import (
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, InvoiceEvent, InvoiceEvents, Order, OrderEvent
+from saleor.order.error_codes import OrderErrorCode
+from saleor.order.models import Order, OrderEvent
from saleor.payment import ChargeStatus, CustomPaymentChoices, PaymentError
from saleor.payment.models import Payment
from saleor.plugins.manager import PluginsManager
@@ -2900,517 +2899,3 @@ def test_user_with_permission_can_clear_private_meta(
assert len(errors) == 0
order_with_meta.refresh_from_db()
assert not order_with_meta.get_value_from_private_metadata(key="foofoo")
-
-
-REQUEST_INVOICE_MUTATION = """
- mutation RequestInvoice($orderId: ID!, $number: String) {
- requestInvoice(
- orderId: $orderId,
- number: $number
- ) {
- invoiceErrors {
- field
- code
- }
- }
- }
-"""
-
-
-CREATE_INVOICE_MUTATION = """
- mutation CreateInvoice($orderId: ID!, $number: String!, $url: String!) {
- createInvoice(
- orderId: $orderId,
- input: {
- number: $number,
- url: $url
- }
- ) {
- invoice {
- number
- url
- }
- invoiceErrors {
- field
- code
- }
- }
- }
-"""
-
-
-REQUEST_DELETE_INVOICE_MUTATION = """
- mutation RequestDeleteInvoice($id: ID!) {
- requestDeleteInvoice(
- id: $id
- ) {
- invoiceErrors {
- field
- code
- }
- }
- }
-"""
-
-
-DELETE_INVOICE_MUTATION = """
- mutation DeleteInvoice($id: ID!) {
- deleteInvoice(
- id: $id
- ) {
- invoiceErrors {
- field
- code
- }
- }
- }
-"""
-
-
-UPDATE_INVOICE_MUTATION = """
- mutation UpdateInvoice($id: ID!, $number: String, $url: String) {
- updateInvoice(
- id: $id,
- input: {
- number: $number,
- url: $url
- }
- ) {
- invoice {
- number
- url
- }
- invoiceErrors {
- field
- code
- }
- }
- }
-"""
-
-
-SEND_INVOICE_MUTATION = """
- mutation SendInvoice($id: ID!) {
- sendInvoiceEmail(
- id: $id
- ) {
- invoiceErrors {
- field
- code
- }
- }
- }
-"""
-
-
-@patch("saleor.plugins.base_plugin.BasePlugin.invoice_request")
-def test_request_invoice(
- plugin_mock, staff_api_client, permission_manage_orders, order
-):
- number = "01/12/2020/TEST"
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- "number": number,
- }
- staff_api_client.post_graphql(
- REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- 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()
-
-
-@patch("saleor.plugins.invoicing.default_storage")
-def test_request_invoice_with_plugin(
- stor_mock, staff_api_client, permission_manage_orders, order, setup_invoicing
-):
- stor_mock.save = Mock(return_value=f"{uuid.uuid4()}.pdf")
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- }
- staff_api_client.post_graphql(
- REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- invoice = Invoice.objects.get(order=order)
- assert invoice.status == InvoiceStatus.READY
-
-
-def test_request_invoice_draft_order(staff_api_client, permission_manage_orders, order):
- order.status = OrderStatus.DRAFT
- order.save()
- number = "01/12/2020/TEST"
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- "number": number,
- }
- response = staff_api_client.post_graphql(
- REQUEST_INVOICE_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"]["requestInvoice"]["invoiceErrors"][0]
- assert error["field"] == "orderId"
- assert error["code"] == InvoiceErrorCode.INVALID_STATUS.name
-
-
-def test_request_invoice_no_billing_address(
- staff_api_client, permission_manage_orders, order
-):
- order.billing_address = None
- order.save()
- number = "01/12/2020/TEST"
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- "number": number,
- }
- response = staff_api_client.post_graphql(
- REQUEST_INVOICE_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"]["requestInvoice"]["invoiceErrors"][0]
- assert error["field"] == "orderId"
- assert error["code"] == InvoiceErrorCode.NOT_READY.name
-
-
-def test_request_invoice_no_number(staff_api_client, permission_manage_orders, order):
- variables = {"orderId": graphene.Node.to_global_id("Order", order.pk)}
- staff_api_client.post_graphql(
- REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- invoice = Invoice.objects.get(order=order.pk)
- assert invoice.number is None
-
-
-def test_request_invoice_invalid_order(staff_api_client, permission_manage_orders):
- variables = {"orderId": "T3JkZXI6MTMzNzEzMzc=", "number": "01/12/2020/TEST"}
- response = staff_api_client.post_graphql(
- REQUEST_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- error = content["data"]["requestInvoice"]["invoiceErrors"][0]
- assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
- assert error["field"] == "orderId"
-
-
-@patch("saleor.plugins.base_plugin.BasePlugin.invoice_delete")
-def test_request_delete_invoice(
- plugin_mock, staff_api_client, permission_manage_orders, order
-):
- invoice = Invoice.objects.create(order=order)
- variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- staff_api_client.post_graphql(REQUEST_DELETE_INVOICE_MUTATION, variables)
- 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")
-def test_request_delete_invoice_invalid_id(
- plugin_mock, staff_api_client, permission_manage_orders
-):
- variables = {"id": graphene.Node.to_global_id("Invoice", 1337)}
- staff_api_client.user.user_permissions.add(permission_manage_orders)
- response = staff_api_client.post_graphql(REQUEST_DELETE_INVOICE_MUTATION, variables)
- content = get_graphql_content(response)
- error = content["data"]["requestDeleteInvoice"]["invoiceErrors"][0]
- assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
- assert error["field"] == "id"
- plugin_mock.assert_not_called()
-
-
-@patch("saleor.plugins.base_plugin.BasePlugin.invoice_delete")
-def test_request_delete_invoice_no_permission(
- plugin_mock, staff_api_client, permission_manage_orders, order
-):
- invoice = Invoice.objects.create(order=order)
- variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(REQUEST_DELETE_INVOICE_MUTATION, variables)
- assert_no_permission(response)
- plugin_mock.assert_not_called()
-
-
-def test_delete_invoice(staff_api_client, permission_manage_orders, order):
- invoice = Invoice.objects.create(order=order)
- variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- DELETE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- 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")
-def test_delete_invoice_invalid_id(
- plugin_mock, staff_api_client, permission_manage_orders
-):
- variables = {"id": graphene.Node.to_global_id("Invoice", 1337)}
- response = staff_api_client.post_graphql(
- DELETE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- error = content["data"]["deleteInvoice"]["invoiceErrors"][0]
- assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
- assert error["field"] == "id"
- plugin_mock.assert_not_called()
-
-
-def test_update_invoice(staff_api_client, permission_manage_orders, order):
- invoice = Invoice.objects.create(order=order)
- number = "01/12/2020/TEST"
- url = "http://www.example.com"
- variables = {
- "id": graphene.Node.to_global_id("Invoice", invoice.pk),
- "number": number,
- "url": url,
- }
- response = staff_api_client.post_graphql(
- UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- invoice.refresh_from_db()
- assert invoice.status == InvoiceStatus.READY
- assert invoice.number == content["data"]["updateInvoice"]["invoice"]["number"]
- assert invoice.url == content["data"]["updateInvoice"]["invoice"]["url"]
-
-
-def test_update_invoice_single_value(staff_api_client, permission_manage_orders, order):
- number = "01/12/2020/TEST"
- invoice = Invoice.objects.create(order=order, number=number)
- url = "http://www.example.com"
- variables = {
- "id": graphene.Node.to_global_id("Invoice", invoice.pk),
- "url": url,
- }
- response = staff_api_client.post_graphql(
- UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- invoice.refresh_from_db()
- assert invoice.status == InvoiceStatus.READY
- assert invoice.number == number
- assert invoice.url == content["data"]["updateInvoice"]["invoice"]["url"]
-
-
-def test_update_invoice_missing_number(
- staff_api_client, permission_manage_orders, order
-):
- invoice = Invoice.objects.create(order=order)
- url = "http://www.example.com"
- variables = {
- "id": graphene.Node.to_global_id("Invoice", invoice.pk),
- "url": url,
- }
- response = staff_api_client.post_graphql(
- UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- invoice.refresh_from_db()
- error = content["data"]["updateInvoice"]["invoiceErrors"][0]
- assert error["code"] == InvoiceErrorCode.URL_OR_NUMBER_NOT_SET.name
- assert error["field"] == "invoice"
- assert invoice.url is None
- assert invoice.status == InvoiceStatus.PENDING
-
-
-def test_update_invoice_invalid_id(staff_api_client, permission_manage_orders):
- variables = {"id": "SW52b2ljZToxMzM3", "number": "01/12/2020/TEST"}
- response = staff_api_client.post_graphql(
- UPDATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- error = content["data"]["updateInvoice"]["invoiceErrors"][0]
- assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
- assert error["field"] == "id"
-
-
-def test_create_invoice(staff_api_client, permission_manage_orders, order):
- number = "01/12/2020/TEST"
- url = "http://www.example.com"
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- "number": number,
- "url": url,
- }
- response = staff_api_client.post_graphql(
- CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- invoice = Invoice.objects.get(order_id=order.pk, url=url, number=number)
- 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_no_billing_address(
- staff_api_client, permission_manage_orders, order
-):
- order.billing_address = None
- order.save()
- number = "01/12/2020/TEST"
- url = "http://www.example.com"
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- "number": number,
- "url": url,
- }
- response = staff_api_client.post_graphql(
- CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- assert not Invoice.objects.filter(
- order_id=order.pk, url=url, number=number
- ).exists()
- error = content["data"]["createInvoice"]["invoiceErrors"][0]
- assert error["field"] == "orderId"
- assert error["code"] == InvoiceErrorCode.NOT_READY.name
-
-
-def test_create_invoice_for_draft_order(
- staff_api_client, permission_manage_orders, order
-):
- order.status = OrderStatus.DRAFT
- order.save()
- number = "01/12/2020/TEST"
- url = "http://www.example.com"
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- "number": number,
- "url": url,
- }
- response = staff_api_client.post_graphql(
- CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- assert not Invoice.objects.filter(
- order_id=order.pk, url=url, number=number
- ).exists()
- error = content["data"]["createInvoice"]["invoiceErrors"][0]
- assert error["field"] == "orderId"
- assert error["code"] == InvoiceErrorCode.INVALID_STATUS.name
-
-
-def test_create_invoice_invalid_id(staff_api_client, permission_manage_orders):
- variables = {
- "orderId": graphene.Node.to_global_id("Order", 1337),
- "number": "01/12/2020/TEST",
- "url": "http://www.example.com",
- }
- response = staff_api_client.post_graphql(
- CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- error = content["data"]["createInvoice"]["invoiceErrors"][0]
- assert error["code"] == InvoiceErrorCode.NOT_FOUND.name
- assert error["field"] == "orderId"
-
-
-def test_create_invoice_empty_params(staff_api_client, permission_manage_orders, order):
- variables = {
- "orderId": graphene.Node.to_global_id("Order", order.pk),
- "number": "",
- "url": "",
- }
- response = staff_api_client.post_graphql(
- CREATE_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- errors = content["data"]["createInvoice"]["invoiceErrors"]
- assert errors[0] == {
- "field": "url",
- "code": InvoiceErrorCode.REQUIRED.name,
- }
- assert errors[1] == {
- "field": "number",
- "code": InvoiceErrorCode.REQUIRED.name,
- }
-
- assert not Invoice.objects.filter(
- order_id=order.pk, status=InvoiceStatus.READY
- ).exists()
-
-
-@patch("saleor.order.emails.send_invoice.delay")
-def test_send_invoice(email_mock, staff_api_client, permission_manage_orders, order):
- number = "01/12/2020/TEST"
- url = "http://www.example.com"
- invoice = Invoice.objects.create(
- order=order, number=number, url=url, status=InvoiceStatus.READY
- )
- variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- SEND_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- 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")
-def test_send_pending_invoice(
- email_mock, staff_api_client, permission_manage_orders, order
-):
- invoice = Invoice.objects.create(
- order=order, number=None, url=None, status=InvoiceStatus.PENDING
- )
- variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- SEND_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- errors = content["data"]["sendInvoiceEmail"]["invoiceErrors"]
- assert errors == [{"field": None, "code": InvoiceErrorCode.NOT_READY.name}]
- email_mock.assert_not_called()
-
-
-@patch("saleor.order.emails.send_invoice.delay")
-def test_send_not_ready_invoice(
- email_mock, staff_api_client, permission_manage_orders, order
-):
- invoice = Invoice.objects.create(
- order=order, number=None, url=None, status=InvoiceStatus.READY
- )
- variables = {"id": graphene.Node.to_global_id("Invoice", invoice.pk)}
- response = staff_api_client.post_graphql(
- SEND_INVOICE_MUTATION, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- errors = content["data"]["sendInvoiceEmail"]["invoiceErrors"]
- [{"field": None, "code": "URL_OR_NUMBER_NOT_SET"}]
- assert errors == [
- {"field": None, "code": InvoiceErrorCode.URL_OR_NUMBER_NOT_SET.name}
- ]
- email_mock.assert_not_called()
diff --git a/tests/conftest.py b/tests/conftest.py
index aa984290b3..b732a47086 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -36,7 +36,7 @@ from saleor.discount.models import (
VoucherTranslation,
)
from saleor.giftcard.models import GiftCard
-from saleor.graphql.order.enums import InvoiceStatus
+from saleor.graphql.invoice.enums import InvoiceStatus
from saleor.menu.models import Menu, MenuItem, MenuItemTranslation
from saleor.menu.utils import update_menu
from saleor.order import OrderStatus
@@ -184,10 +184,7 @@ def setup_vatlayer(settings):
@pytest.fixture
def setup_invoicing(settings):
settings.PLUGINS = ["saleor.plugins.invoicing.plugin.InvoicingPlugin"]
- data = {
- "active": True,
- }
- PluginConfiguration.objects.create(identifier=InvoicingPlugin.PLUGIN_ID, **data)
+ PluginConfiguration.objects.create(identifier=InvoicingPlugin.PLUGIN_ID)
return settings