Skip to content

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

Invoice plugin

Tomasz Szymanskice825a1733f4
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 9baada7979..8962098421 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -517,9 +517,10 @@ class OrderClearPrivateMeta(ClearMetaBaseMutation):
public = False
-class RequestInvoice(BaseMutation):
+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"
@@ -544,7 +545,8 @@ class RequestInvoice(BaseMutation):
info.context.plugins.invoice_request(
order=order, invoice=invoice, number=data.get("number")
)
- return RequestInvoice()
+ invoice.refresh_from_db()
+ return RequestInvoice(invoice=invoice)
class CreateInvoiceInput(graphene.InputObjectType):
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index ca7922b578..4363e1d5f5 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -289,7 +289,7 @@ class Invoice(CountableDjangoObjectType):
description = "Represents an Invoice."
interfaces = [relay.Node]
model = models.Invoice
- only_fields = ["id", "number", "url"]
+ only_fields = ["id", "number", "url", "status"]
class Order(CountableDjangoObjectType):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 70da1283ec..da211b03fa 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1959,6 +1959,7 @@ type Invoice implements Node {
id: ID!
number: String
url: String
+ status: String!
}
type InvoiceError {
@@ -4021,6 +4022,7 @@ type RequestEmailChange {
type RequestInvoice {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
invoiceErrors: [InvoiceError!]!
+ invoice: Invoice
}
type RequestPasswordReset {
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 29253f1b41..3d9b94bc14 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -531,3 +531,7 @@ class Invoice(ModelWithMetadata):
if url is not None:
self.url = url
self.save()
+
+ def fullfill_invoice(self):
+ self.status = InvoiceStatus.READY
+ self.save()
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 0eae8b225e..20804cbf52 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,16 +1,9 @@
-import os
from functools import wraps
-from uuid import uuid4
from django.conf import settings
-from django.contrib.staticfiles import finders as static_finders
-from django.core.files.base import ContentFile
-from django.core.files.storage import default_storage
from django.db import transaction
-from django.template.loader import get_template
from django.utils import timezone
from prices import Money, TaxedMoney
-from weasyprint import HTML
from ..account.models import User
from ..core.taxes import zero_money
@@ -342,57 +335,3 @@ def get_voucher_discount_for_order(order: Order) -> Money:
def match_orders_with_new_user(user: User) -> None:
Order.objects.confirmed().filter(user_email=user.email, user=None).update(user=user)
-
-
-def chunk_products(products, product_limit):
- """Split products to list of chunks.
-
- Each chunk represents products per page, product_limit defines chunk size.
- """
- chunks = []
- for i in range(0, len(products), product_limit):
- limit = i + product_limit
- chunks.append(products[i:limit])
- return chunks
-
-
-def get_product_limit_first_page(products):
- MAX_PRODUCTS_WITH_TABLE = 3
- MAX_PRODUCTS_WITHOUT_TABLE = 4
-
- if len(products) < MAX_PRODUCTS_WITHOUT_TABLE:
- return MAX_PRODUCTS_WITH_TABLE
-
- return MAX_PRODUCTS_WITHOUT_TABLE
-
-
-def generate_invoice_pdf_for_order(invoice):
- logo_path = static_finders.find("images/logo.svg")
- font_path = os.path.join(
- settings.PROJECT_ROOT, "templates", "invoices", "inter.ttf"
- )
-
- MAX_PRODUCTS_PER_PAGE = 13
-
- all_products = invoice.order.lines.all()
-
- product_limit_first_page = get_product_limit_first_page(all_products)
-
- products_first_page = all_products[:product_limit_first_page]
- rest_of_products = chunk_products(
- all_products[product_limit_first_page:], MAX_PRODUCTS_PER_PAGE
- )
-
- rendered_template = get_template("invoices/invoice.html").render(
- {
- "invoice": invoice,
- "creation_date": invoice.created.strftime("%d %b %Y"),
- "order": invoice.order,
- "logo_path": f"file://{logo_path}",
- "font_path": f"file://{font_path}",
- "products_first_page": products_first_page,
- "rest_of_products": rest_of_products,
- }
- )
- content_file = ContentFile(HTML(string=rendered_template).write_pdf())
- return default_storage.save(f"{uuid4()}.pdf", content_file)
diff --git a/saleor/plugins/invoicing/__init__.py b/saleor/plugins/invoicing/__init__.py
new file mode 100644
index 0000000000..417aa7d2c2
--- /dev/null
+++ b/saleor/plugins/invoicing/__init__.py
@@ -0,0 +1,89 @@
+import os
+import re
+from datetime import datetime
+from uuid import uuid4
+
+from django.conf import settings
+from django.contrib.staticfiles import finders as static_finders
+from django.core.files.base import ContentFile
+from django.core.files.storage import default_storage
+from django.template.loader import get_template
+from weasyprint import HTML
+
+from ...order.models import Invoice
+
+
+def make_full_invoice_number(number=1):
+ month_and_year = datetime.now().strftime("%m/%Y")
+ return f"{number}/{month_and_year}"
+
+
+def parse_invoice_number(invoice):
+ number = re.match(r"^(\d+)\/", invoice.number).group(1)
+ return int(number)
+
+
+def generate_invoice_number():
+ last_invoice = Invoice.objects.last()
+ if not last_invoice or not last_invoice.number:
+ return make_full_invoice_number()
+
+ try:
+ last_number = parse_invoice_number(last_invoice)
+ return make_full_invoice_number(last_number + 1)
+ except (IndexError, ValueError):
+ return make_full_invoice_number()
+
+
+def chunk_products(products, product_limit):
+ """Split products to list of chunks.
+
+ Each chunk represents products per page, product_limit defines chunk size.
+ """
+ chunks = []
+ for i in range(0, len(products), product_limit):
+ limit = i + product_limit
+ chunks.append(products[i:limit])
+ return chunks
+
+
+def get_product_limit_first_page(products):
+ MAX_PRODUCTS_WITH_TABLE = 3
+ MAX_PRODUCTS_WITHOUT_TABLE = 4
+
+ if len(products) < MAX_PRODUCTS_WITHOUT_TABLE:
+ return MAX_PRODUCTS_WITH_TABLE
+
+ return MAX_PRODUCTS_WITHOUT_TABLE
+
+
+def generate_invoice_pdf(invoice):
+ logo_path = static_finders.find("images/logo.svg")
+ font_path = os.path.join(
+ settings.PROJECT_ROOT, "templates", "invoices", "inter.ttf"
+ )
+
+ MAX_PRODUCTS_PER_PAGE = 13
+
+ all_products = invoice.order.lines.all()
+
+ product_limit_first_page = get_product_limit_first_page(all_products)
+
+ products_first_page = all_products[:product_limit_first_page]
+ rest_of_products = chunk_products(
+ all_products[product_limit_first_page:], MAX_PRODUCTS_PER_PAGE
+ )
+
+ rendered_template = get_template("invoices/invoice.html").render(
+ {
+ "invoice": invoice,
+ "creation_date": invoice.created.strftime("%d %b %Y"),
+ "order": invoice.order,
+ "logo_path": f"file://{logo_path}",
+ "font_path": f"file://{font_path}",
+ "products_first_page": products_first_page,
+ "rest_of_products": rest_of_products,
+ }
+ )
+ content_file = ContentFile(HTML(string=rendered_template).write_pdf())
+ return default_storage.save(f"{uuid4()}.pdf", content_file)
diff --git a/saleor/plugins/invoicing/plugin.py b/saleor/plugins/invoicing/plugin.py
new file mode 100644
index 0000000000..b50bb145cc
--- /dev/null
+++ b/saleor/plugins/invoicing/plugin.py
@@ -0,0 +1,30 @@
+from datetime import datetime
+from typing import Any, Optional
+
+import pytz
+
+from ...order.models import Invoice, Order
+from ..base_plugin import BasePlugin
+from . import generate_invoice_number, generate_invoice_pdf
+
+
+class InvoicingPlugin(BasePlugin):
+ PLUGIN_ID = "mirumee.invoicing"
+ PLUGIN_NAME = "Invoicing"
+ DEFAULT_ACTIVE = True
+ PLUGIN_DESCRIPTION = "Default saleor plugin that handles invoice creation."
+
+ def invoice_request(
+ self,
+ order: "Order",
+ invoice: "Invoice",
+ number: Optional[str],
+ previous_value: Any,
+ ) -> Any:
+ invoice.update_invoice(number=generate_invoice_number())
+ invoice.created = datetime.now(tz=pytz.utc)
+ invoice.save()
+ file_name = generate_invoice_pdf(invoice)
+ invoice.update_invoice(url=f"http://localhost:8000/invoice/{file_name}")
+ invoice.fullfill_invoice()
+ return invoice
diff --git a/saleor/settings.py b/saleor/settings.py
index 2a5e6303d9..c3075a2c6f 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -509,6 +509,7 @@ PLUGINS_MANAGER = "saleor.plugins.manager.PluginsManager"
PLUGINS = [
"saleor.plugins.avatax.plugin.AvataxPlugin",
+ "saleor.plugins.invoicing.plugin.InvoicingPlugin",
"saleor.plugins.vatlayer.plugin.VatlayerPlugin",
"saleor.plugins.webhook.plugin.WebhookPlugin",
"saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin",
diff --git a/templates/invoices/invoice.html b/templates/invoices/invoice.html
index f44eba3bac..addaa422e1 100644
--- a/templates/invoices/invoice.html
+++ b/templates/invoices/invoice.html
@@ -217,7 +217,12 @@
<span class="header-title">
{% trans "INVOICE INFORMATION" context "Invoice PDF header" %}
</span>
- <br />
+ <span class="header-category">
+ {% trans "Invoice number:" context "Invoice PDF header: Invoice number" %}
+ </span>
+ <div class="padded-font-sm"></div>
+ <span class="header-item">{{ invoice.number }}</span>
+ <div class="padded-font"></div>
<span class="header-category">
{% trans "Order:" context "Invoice PDF header: order number" %}
</span>
diff --git a/tests/conftest.py b/tests/conftest.py
index c74ea67258..aa984290b3 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -47,6 +47,7 @@ from saleor.order.utils import recalculate_order
from saleor.page.models import Page, PageTranslation
from saleor.payment import ChargeStatus, TransactionKind
from saleor.payment.models import Payment
+from saleor.plugins.invoicing.plugin import InvoicingPlugin
from saleor.plugins.models import PluginConfiguration
from saleor.plugins.vatlayer.plugin import VatlayerPlugin
from saleor.product import AttributeInputType
@@ -180,6 +181,16 @@ def setup_vatlayer(settings):
return settings
+def setup_invoicing(settings):
+ settings.PLUGINS = ["saleor.plugins.invoicing.plugin.InvoicingPlugin"]
+ data = {
+ "active": True,
+ }
+ PluginConfiguration.objects.create(identifier=InvoicingPlugin.PLUGIN_ID, **data)
+ return settings
+
+
@pytest.fixture(autouse=True)
def setup_dummy_gateway(settings):
settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]
diff --git a/tests/plugins/test_invoicing.py b/tests/plugins/test_invoicing.py
new file mode 100644
index 0000000000..9a770eff7b
--- /dev/null
+++ b/tests/plugins/test_invoicing.py
@@ -0,0 +1,61 @@
+from datetime import datetime
+from unittest.mock import Mock, patch
+from uuid import UUID
+
+from saleor.plugins.invoicing import (
+ chunk_products,
+ generate_invoice_pdf,
+ get_product_limit_first_page,
+)
+
+
+def test_request_invoice(setup_invoicing):
+ pass
+
+
+def test_chunk_products(product):
+ assert chunk_products([product] * 3, 3) == [[product] * 3]
+ assert chunk_products([product] * 5, 3) == [[product] * 3, [product] * 2]
+ assert chunk_products([product] * 8, 3) == [
+ [product] * 3,
+ [product] * 3,
+ [product] * 2,
+ ]
+
+
+def test_get_product_limit_first_page(product):
+ assert get_product_limit_first_page([product] * 3) == 3
+ assert get_product_limit_first_page([product] * 4) == 4
+ assert get_product_limit_first_page([product] * 16) == 4
+
+
+@patch("saleor.plugins.invoicing.static_finders")
+@patch("saleor.plugins.invoicing.get_template")
+@patch("saleor.plugins.invoicing.default_storage")
+@patch("saleor.plugins.invoicing.os")
+def test_generate_invoice_pdf_for_order(
+ os_mock, storage_mock, get_template_mock, static_mock, fulfilled_order
+):
+ file_path = "/dev/null"
+ static_mock.find.return_value = file_path
+ storage_mock.save = Mock()
+ get_template_mock.return_value.render = Mock(return_value="<html></html>")
+ os_mock.path.join.return_value = "test"
+
+ generate_invoice_pdf(fulfilled_order.invoices.first())
+
+ get_template_mock.return_value.render.assert_called_once_with(
+ {
+ "invoice": fulfilled_order.invoices.first(),
+ "creation_date": datetime.today().strftime("%d %b %Y"),
+ "order": fulfilled_order,
+ "logo_path": f"file://{file_path}",
+ "font_path": "file://test",
+ "products_first_page": list(fulfilled_order.lines.all()),
+ "rest_of_products": [],
+ }
+ )
+
+ file_name, extension = storage_mock.save.call_args[0][0].split(".")
+ assert UUID(file_name, version=4)
+ assert extension == "pdf"
diff --git a/tests/test_order.py b/tests/test_order.py
index 6ab7d75686..b197d2a844 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -1,7 +1,5 @@
-from datetime import datetime
from decimal import Decimal
from unittest.mock import MagicMock, Mock, patch
-from uuid import UUID
import pytest
from prices import Money, TaxedMoney
@@ -22,10 +20,7 @@ from saleor.order.templatetags.order_lines import display_translated_order_line_
from saleor.order.utils import (
add_variant_to_draft_order,
change_order_line_quantity,
- chunk_products,
delete_order_line,
- generate_invoice_pdf_for_order,
- get_product_limit_first_page,
get_voucher_discount_for_order,
recalculate_order,
restock_fulfillment_lines,
@@ -730,51 +725,3 @@ def test_email_sent_event_without_user_and_user_pk(order):
"email": order.get_customer_email(),
"email_type": email_type,
}
-
-
-def test_chunk_products(product):
- assert chunk_products([product] * 3, 3) == [[product] * 3]
- assert chunk_products([product] * 5, 3) == [[product] * 3, [product] * 2]
- assert chunk_products([product] * 8, 3) == [
- [product] * 3,
- [product] * 3,
- [product] * 2,
- ]
-
-
-def test_get_product_limit_first_page(product):
- assert get_product_limit_first_page([product] * 3) == 3
- assert get_product_limit_first_page([product] * 4) == 4
- assert get_product_limit_first_page([product] * 16) == 4
-
-
-@patch("saleor.order.utils.static_finders")
-@patch("saleor.order.utils.get_template")
-@patch("saleor.order.utils.default_storage")
-@patch("saleor.order.utils.os")
-def test_generate_invoice_pdf_for_order(
- os_mock, storage_mock, get_template_mock, static_mock, fulfilled_order
-):
- file_path = "/dev/null"
- static_mock.find.return_value = file_path
- storage_mock.save = Mock()
- get_template_mock.return_value.render = Mock(return_value="<html></html>")
- os_mock.path.join.return_value = "test"
-
- generate_invoice_pdf_for_order(fulfilled_order.invoices.first())
-
- get_template_mock.return_value.render.assert_called_once_with(
- {
- "invoice": fulfilled_order.invoices.first(),
- "creation_date": datetime.today().strftime("%d %b %Y"),
- "order": fulfilled_order,
- "logo_path": f"file://{file_path}",
- "font_path": "file://test",
- "products_first_page": list(fulfilled_order.lines.all()),
- "rest_of_products": [],
- }
- )
-
- file_name, extension = storage_mock.save.call_args[0][0].split(".")
- assert UUID(file_name, version=4)
- assert extension == "pdf"