Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Order confirmation backend (#6498)
Tomasz Szymańskib51ac2305e48
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1b4b98b3a5..22c754b752 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ All notable, unreleased changes to this project will be documented in this file.- Drop deprecated service accounts and webhooks API - #6431 by @maarcingebala- Add editorjs sanitizer - #6456 by @IKarbowiak- Add generic FileUpload mutation - #6470 by @IKarbowiak+- Order confirmation backend - #6498 by @tomaszszymanski129- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki- Fix password reset request - #6351 by @Manfred-Madelaine-pro, Ambroise and Pierre- Add possibility to exclude products from shipping method - #6506 by @korycinsdiff --git a/locale/en/LC_MESSAGES/django.po b/locale/en/LC_MESSAGES/django.poindex c4e06b476d..9730907e2a 100644--- a/locale/en/LC_MESSAGES/django.po+++ b/locale/en/LC_MESSAGES/django.po@@ -8,7 +8,7 @@ msgid ""msgstr """Project-Id-Version: master\n""Report-Msgid-Bugs-To: \n"-"POT-Creation-Date: 2020-10-23 07:04+0000\n"+"POT-Creation-Date: 2020-11-10 12:31+0000\n""PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n""Last-Translator: FULL NAME <EMAIL@ADDRESS>\n""Language-Team: LANGUAGE <[email protected]>\n"@@ -374,6 +374,88 @@ msgctxt "Order confirmation e-mail text"msgid "No shipping required"msgstr ""+#: templates/templated_email/order/confirmed_order.email:6+#, python-format+msgctxt "Order confirmed e-mail subject"+msgid "Order %(order)s details"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:13+msgctxt "Order confirmed e-mail text"+msgid ""+"\n"+"Your order has been confirmed by staff. Below is the list of ordered "+"products.\n"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:17+#, python-format+msgctxt "Order confirmed e-mail payment details"+msgid ""+"\n"+"To see your order details please visit:\n"+"%(order_details_url)s\n"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:25+msgctxt "Order confirmed e-mail table header"+msgid "Order summary"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:26+msgctxt "Order confirmed e-mail table header"+msgid "Subtotal"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:27+msgctxt "Order confirmed e-mail table header"+msgid "Shipping"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:28+msgctxt "Order confirmed e-mail table header"+msgid "Taxes (included)"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:28+msgctxt "Order confirmed e-mail table header"+msgid "Taxes"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:29+msgctxt "Order confirmed e-mail table header"+msgid "Discount:"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:30+msgctxt "Order confirmed e-mail table header"+msgid "Total"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:32+#: templates/templated_email/source/confirmed_order.mjml:35+msgctxt "Order confirmed e-mail billing address"+msgid "Billing address"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:33+#: templates/templated_email/source/confirmed_order.mjml:45+msgctxt "Order confirmed e-mail text"+msgid "No billing address"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:35+#: templates/templated_email/source/confirmed_order.mjml:36+msgctxt "Order confirmed e-mail shipping address"+msgid "Shipping address"+msgstr ""++#: templates/templated_email/order/confirmed_order.email:36+#: templates/templated_email/source/confirmed_order.mjml:52+msgctxt "Order confirmed e-mail text"+msgid "No shipping required"+msgstr ""+#: templates/templated_email/order/order_cancel.email:4#, python-formatmsgctxt "Order cancel e-mail subject"@@ -475,6 +557,7 @@ msgstr ""#: templates/templated_email/source/confirm_fulfillment.mjml:13#: templates/templated_email/source/confirm_order.mjml:14#: templates/templated_email/source/confirm_payment.mjml:13+#: templates/templated_email/source/confirmed_order.mjml:14#: templates/templated_email/source/email_changed_notification.mjml:13#: templates/templated_email/source/export_failed.mjml:13#: templates/templated_email/source/export_products_file.mjml:13@@ -547,6 +630,21 @@ msgctxt "Payment confirmation e-mail text"msgid "Thank you for your payment. Your payment was successfully processed."msgstr ""+#: templates/templated_email/source/confirmed_order.mjml:18+#, python-format+msgctxt "Order confirmed e-mail text with order details"+msgid ""+"Your order has been confirmed by staff. To see your order details please "+"visit: <a href=\"%(order_details_url)s\">%(order_details_url)s</a>"+msgstr ""++#: templates/templated_email/source/confirmed_order.mjml:22+msgctxt "Order confirmed e-mail text"+msgid ""+"Your order has been confirmed by staff. Below is the list of ordered "+"products."+msgstr ""+#: templates/templated_email/source/email_changed_notification.mjml:16#, python-formatmsgctxt "Email change e-mail text"diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex e1a00ab5cb..89120f8a43 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -2,6 +2,7 @@ from datetime import datefrom decimal import Decimalfrom typing import Iterable, List, Optional, Tuple+from django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.utils.encoding import smart_text@@ -26,6 +27,7 @@ from ..discount.utils import (increase_voucher_usage,remove_voucher_usage_by_customer,)+from ..order import OrderStatusfrom ..order.actions import order_createdfrom ..order.emails import send_order_confirmation, send_staff_order_confirmationfrom ..order.models import Order, OrderLine@@ -254,8 +256,18 @@ def _create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:total_price_left = order_data.pop("total_price_left")order_lines = order_data.pop("lines")+ # TODO: refactor to use request.site / info.context site+ site_settings = Site.objects.get_current().settings+ status = (+ OrderStatus.UNFULFILLED+ if site_settings.automatically_confirm_all_new_orders+ else OrderStatus.UNCONFIRMED+ )order = Order.objects.create(- **order_data, checkout_token=checkout.token, channel=checkout.channel+ **order_data,+ checkout_token=checkout.token,+ status=status,+ channel=checkout.channel,)for line in order_lines:line.order_id = order.pkdiff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 9c1511b6c4..4bb79e1a38 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -43,16 +43,14 @@ def test_create_order_captured_payment_creates_expected_events()flush_post_commit_hooks()- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-(order_placed_event,payment_captured_event,order_fully_paid_event,payment_email_sent_event,+ order_confirmed_event,order_placed_email_sent_event,- ) = order_events # type: OrderEvent+ ) = order.events.all() # type: OrderEvent# Ensure the correct order event was created# is the event the expected type@@ -107,6 +105,18 @@ def test_create_order_captured_payment_creates_expected_events("email_type": OrderEventsEmails.PAYMENT,}+ # Ensure the correct order confirmed event was created+ # should be order confirmed event+ assert order_confirmed_event.type == OrderEvents.CONFIRMED+ # ensure the user is checkout user+ assert order_confirmed_event.user == checkout_user+ # ensure the order confirmed event is related to order+ assert order_confirmed_event.order is order+ # ensure a date was set+ assert order_confirmed_event.date+ # ensure the event parameters are empty+ assert order_confirmed_event.parameters == {}+# Ensure the correct email sent event was created# should be email sent eventassert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT@@ -164,16 +174,14 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user()flush_post_commit_hooks()- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-(order_placed_event,payment_captured_event,order_fully_paid_event,payment_email_sent_event,+ order_confirmed_event,order_placed_email_sent_event,- ) = order_events # type: OrderEvent+ ) = order.events.all() # type: OrderEvent# Ensure the correct order event was created# is the event the expected type@@ -228,6 +236,18 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user("email_type": OrderEventsEmails.PAYMENT,}+ # Ensure the correct order confirmed event was created+ # should be order confirmed event+ assert order_confirmed_event.type == OrderEvents.CONFIRMED+ # ensure the user is checkout user+ assert order_confirmed_event.user == checkout_user+ # ensure the order confirmed event is related to order+ assert order_confirmed_event.order is order+ # ensure a date was set+ assert order_confirmed_event.date+ # ensure the event parameters are empty+ assert order_confirmed_event.parameters == {}+# Ensure the correct email sent event was created# should be email sent eventassert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT@@ -277,14 +297,12 @@ def test_create_order_preauth_payment_creates_expected_events()flush_post_commit_hooks()- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-(order_placed_event,payment_authorized_event,+ order_confirmed_event,order_placed_email_sent_event,- ) = order_events # type: OrderEvent+ ) = order.events.all() # type: OrderEvent# Ensure the correct order event was created# is the event the expected type@@ -312,6 +330,18 @@ def test_create_order_preauth_payment_creates_expected_events(assert "payment_id" in payment_authorized_event.parameters.keys()assert "payment_gateway" in payment_authorized_event.parameters.keys()+ # Ensure the correct order confirmed event was created+ # should be order confirmed event+ assert order_confirmed_event.type == OrderEvents.CONFIRMED+ # ensure the user is checkout user+ assert order_confirmed_event.user == checkout_user+ # ensure the order confirmed event is related to order+ assert order_confirmed_event.order is order+ # ensure a date was set+ assert order_confirmed_event.date+ # ensure the event parameters are empty+ assert order_confirmed_event.parameters == {}+# Ensure the correct email sent event was created# should be email sent eventassert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENT@@ -369,14 +399,12 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user()flush_post_commit_hooks()- # Ensure only two events were created, and retrieve them- order_events = order.events.all()-(order_placed_event,payment_captured_event,+ order_confirmed_event,order_placed_email_sent_event,- ) = order_events # type: OrderEvent+ ) = order.events.all() # type: OrderEvent# Ensure the correct order event was created# is the event the expected type@@ -404,6 +432,18 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(assert "payment_id" in payment_captured_event.parameters.keys()assert "payment_gateway" in payment_captured_event.parameters.keys()+ # Ensure the correct order confirmed event was created+ # should be order confirmed event+ assert order_confirmed_event.type == OrderEvents.CONFIRMED+ # ensure the user is checkout user+ assert order_confirmed_event.user == checkout_user+ # ensure the order confirmed event is related to order+ assert order_confirmed_event.order is order+ # ensure a date was set+ assert order_confirmed_event.date+ # ensure the event parameters are empty+ assert order_confirmed_event.parameters == {}+# Ensure the correct email sent event was created# should be email sent eventassert order_placed_email_sent_event.type == OrderEvents.EMAIL_SENTdiff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex a42d0ca85c..24fbbd8d3f 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -50,6 +50,7 @@ from ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelfrom ...discount.utils import fetch_discountsfrom ...giftcard.models import GiftCardfrom ...menu.models import Menu+from ...order import OrderStatusfrom ...order.models import Fulfillment, Order, OrderLinefrom ...order.utils import update_order_statusfrom ...page.models import Page, PageType@@ -633,6 +634,9 @@ def create_fake_order(discounts, max_order_lines=5):)customer = random.choice([None, customers.first()])+ # 20% chance to be unconfirmed order.+ will_be_unconfirmed = random.choice([0, 0, 0, 0, 1])+if customer:address = customer.default_shipping_addressorder_data = {@@ -665,6 +669,8 @@ def create_fake_order(discounts, max_order_lines=5):"shipping_price": shipping_price,})+ if will_be_unconfirmed:+ order_data["status"] = OrderStatus.UNCONFIRMEDorder = Order.objects.create(**order_data)lines = create_order_lines(order, discounts, random.randrange(1, max_order_lines))@@ -676,7 +682,10 @@ def create_fake_order(discounts, max_order_lines=5):order.save()create_fake_payment(order=order)- create_fulfillments(order)++ if not will_be_unconfirmed:+ create_fulfillments(order)+return orderdiff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex 2ff9d21eae..b43e131524 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -9,6 +9,7 @@ from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.models import Checkoutfrom ....core.exceptions import InsufficientStockfrom ....core.taxes import zero_money+from ....order import OrderStatusfrom ....order.models import Orderfrom ....payment import ChargeStatus, PaymentError, TransactionKindfrom ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPING@@ -143,7 +144,10 @@ def test_checkout_complete_with_inactive_channel(@pytest.mark.integration+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")def test_checkout_complete(+ order_confirmed_mock,+ site_settings,user_api_client,checkout_with_gift_card,gift_card,@@ -166,6 +170,9 @@ def test_checkout_complete(checkout_line_quantity = checkout_line.quantitycheckout_line_variant = checkout_line.variant+ site_settings.automatically_confirm_all_new_orders = True+ site_settings.save()+total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)payment = payment_dummypayment.is_active = True@@ -189,6 +196,7 @@ def test_checkout_complete(order_token = data["order"]["token"]assert Order.objects.count() == orders_count + 1order = Order.objects.first()+ assert order.status == OrderStatus.UNFULFILLEDassert order.token == order_tokenassert order.redirect_url == redirect_urlassert order.total.gross == total.gross@@ -212,6 +220,36 @@ def test_checkout_complete(assert not Checkout.objects.filter(pk=checkout.pk).exists(), "Checkout should have been deleted"+ order_confirmed_mock.assert_called_once_with(order)+++@patch("saleor.plugins.manager.PluginsManager.order_confirmed")+def test_checkout_complete_requires_confirmation(+ order_confirmed_mock,+ user_api_client,+ site_settings,+ payment_dummy,+ checkout_ready_to_complete,+):+ site_settings.automatically_confirm_all_new_orders = False+ site_settings.save()+ payment = payment_dummy+ payment.checkout = checkout_ready_to_complete+ payment.save()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout_ready_to_complete.pk)+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)++ order_id = int(+ graphene.Node.from_global_id(+ content["data"]["checkoutComplete"]["order"]["id"]+ )[1]+ )+ order = Order.objects.get(pk=order_id)+ assert order.status == OrderStatus.UNCONFIRMED+ order_confirmed_mock.assert_not_called()@pytest.mark.integrationdiff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex 6301505d34..fcbf242878 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -23,6 +23,7 @@ from ...shipping import error_codes as shipping_error_codesfrom ...warehouse import error_codes as warehouse_error_codesfrom ...webhook import error_codes as webhook_error_codesfrom ...wishlist import error_codes as wishlist_error_codes+from ..shop import error_codes as shop_error_codesfrom .utils import str_to_enum# FIXME CoreTaxRateType should be removed after we will drop old api fields dedicated@@ -97,6 +98,9 @@ DiscountErrorCode = graphene.Enum.from_enum(discount_error_codes.DiscountErrorCoPluginErrorCode = graphene.Enum.from_enum(plugin_error_codes.PluginErrorCode)GiftCardErrorCode = graphene.Enum.from_enum(giftcard_error_codes.GiftCardErrorCode)MenuErrorCode = graphene.Enum.from_enum(menu_error_codes.MenuErrorCode)+OrderSettingsErrorCode = graphene.Enum.from_enum(+ shop_error_codes.OrderSettingsErrorCode+)MetadataErrorCode = graphene.Enum.from_enum(core_error_codes.MetadataErrorCode)OrderErrorCode = graphene.Enum.from_enum(order_error_codes.OrderErrorCode)InvoiceErrorCode = graphene.Enum.from_enum(invoice_error_codes.InvoiceErrorCode)diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex ee7c70ff85..3225a3b9c4 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -17,6 +17,7 @@ from ..enums import (MenuErrorCode,MetadataErrorCode,OrderErrorCode,+ OrderSettingsErrorCode,PageErrorCode,PaymentErrorCode,PermissionEnum,@@ -145,6 +146,10 @@ class MenuError(Error):code = MenuErrorCode(description="The error code.", required=True)+class OrderSettingsError(Error):+ code = OrderSettingsErrorCode(description="The error code.", required=True)++class MetadataError(Error):code = MetadataErrorCode(description="The error code.", required=True)diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.pyindex 0eb7382063..0b9071364c 100644--- a/saleor/graphql/core/utils/error_codes.py+++ b/saleor/graphql/core/utils/error_codes.py@@ -22,6 +22,7 @@ from ....payment.error_codes import PaymentErrorCodefrom ....plugins.error_codes import PluginErrorCodefrom ....product.error_codes import ProductErrorCodefrom ....shipping.error_codes import ShippingErrorCode+from ...shop.error_codes import OrderSettingsErrorCodeDJANGO_VALIDATORS_ERROR_CODES = ["invalid",@@ -67,6 +68,7 @@ SALEOR_ERROR_CODE_ENUMS = [OrderErrorCode,PageErrorCode,PaymentErrorCode,+ OrderSettingsErrorCode,PermissionGroupErrorCode,ProductErrorCode,ShippingErrorCode,diff --git a/saleor/graphql/order/enums.py b/saleor/graphql/order/enums.pyindex 33df7d7efc..9b3c17aae2 100644--- a/saleor/graphql/order/enums.py+++ b/saleor/graphql/order/enums.py@@ -11,6 +11,7 @@ class OrderStatusFilter(graphene.Enum):READY_TO_FULFILL = "ready_to_fulfill"READY_TO_CAPTURE = "ready_to_capture"UNFULFILLED = "unfulfilled"+ UNCONFIRMED = "unconfirmed"PARTIALLY_FULFILLED = "partially fulfilled"FULFILLED = "fulfilled"CANCELED = "canceled"diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 0d962b36ef..b4cfa0e084 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -11,6 +11,7 @@ from ....order.actions import (clean_mark_order_as_paid,mark_order_as_paid,order_captured,+ order_confirmed,order_refunded,order_shipping_updated,order_voided,@@ -19,7 +20,7 @@ from ....order.error_codes import OrderErrorCodefrom ....order.utils import get_valid_shipping_methods_for_order, update_order_pricesfrom ....payment import CustomPaymentChoices, PaymentError, TransactionKind, gatewayfrom ...account.types import AddressInput-from ...core.mutations import BaseMutation+from ...core.mutations import BaseMutation, ModelMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types.common import OrderErrorfrom ...core.utils import validate_required_string_field@@ -486,3 +487,45 @@ class OrderRefund(BaseMutation):if transaction.kind == TransactionKind.REFUND:order_refunded(order, info.context.user, amount, payment)return OrderRefund(order=order)+++class OrderConfirm(ModelMutation):+ order = graphene.Field(Order, description="Order which has been confirmed.")++ class Arguments:+ id = graphene.ID(description="ID of an order to confirm.", required=True)++ class Meta:+ description = "Confirms an unconfirmed order by changing status to unfulfilled."+ model = models.Order+ permissions = (OrderPermissions.MANAGE_ORDERS,)+ error_type_class = OrderError+ error_type_field = "order_errors"++ @classmethod+ def get_instance(cls, info, **data):+ instance = super().get_instance(info, **data)+ if instance.status != OrderStatus.UNCONFIRMED:+ raise ValidationError(+ {+ "id": ValidationError(+ "Provided order id belongs to an order with status "+ "different than unconfirmed.",+ code=OrderErrorCode.INVALID,+ )+ }+ )+ return instance++ @classmethod+ @transaction.atomic+ def perform_mutation(cls, root, info, **data):+ order = cls.get_instance(info, **data)+ order.status = OrderStatus.UNFULFILLED+ order.save(update_fields=["status"])+ payment = order.get_last_payment()+ if payment and payment.is_authorized and payment.can_capture():+ gateway.capture(payment)+ order_captured(order, info.context.user, payment.total, payment)+ order_confirmed(order, info.context.user, send_confirmation_email=True)+ return OrderConfirm(order=order)diff --git a/saleor/graphql/order/resolvers.py b/saleor/graphql/order/resolvers.pyindex 653543b9a6..53ab8424d7 100644--- a/saleor/graphql/order/resolvers.py+++ b/saleor/graphql/order/resolvers.py@@ -21,6 +21,8 @@ def filter_orders(qs, info, created, status):qs = qs.ready_to_fulfill()elif status == OrderStatusFilter.READY_TO_CAPTURE:qs = qs.ready_to_capture()+ elif status == OrderStatusFilter.UNCONFIRMED:+ qs = qs.ready_to_confirm()# DEPRECATED: Will be removed in Saleor 2.11, use the `filter` field instead.# filter orders by creation date@@ -31,7 +33,7 @@ def filter_orders(qs, info, created, status):def resolve_orders(info, created, status, channel_slug, **_kwargs):- qs = models.Order.objects.confirmed()+ qs = models.Order.objects.non_draft()if channel_slug:qs = qs.filter(channel__slug=str(channel_slug))return filter_orders(qs, info, created, status)@@ -49,7 +51,7 @@ def resolve_orders_total(_info, period, channel_slug):if not channel:return Noneqs = (- models.Order.objects.confirmed()+ models.Order.objects.non_draft().exclude(status=OrderStatus.CANCELED).filter(channel__slug=str(channel_slug)))diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex a3a2c4d7b3..0f3040ffd8 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -28,6 +28,7 @@ from .mutations.orders import (OrderAddNote,OrderCancel,OrderCapture,+ OrderConfirm,OrderMarkAsPaid,OrderRefund,OrderUpdate,@@ -158,6 +159,7 @@ class OrderMutations(graphene.ObjectType):order_add_note = OrderAddNote.Field()order_cancel = OrderCancel.Field()order_capture = OrderCapture.Field()+ order_confirm = OrderConfirm.Field()order_fulfill = OrderFulfill.Field()order_fulfillment_cancel = FulfillmentCancel.Field()order_fulfillment_update_tracking = FulfillmentUpdateTracking.Field()diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex d26996eaa6..13192ff3f5 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -99,6 +99,12 @@ def orders(customer_user, channel_USD, channel_PLN):token=uuid.uuid4(),channel=channel_PLN,),+ Order(+ user=customer_user,+ status=OrderStatus.UNCONFIRMED,+ token=uuid.uuid4(),+ channel=channel_PLN,+ ),])@@ -520,7 +526,9 @@ def test_order_query_gift_cards()-def test_order_query_draft_excluded(staff_api_client, permission_manage_orders, orders):+def test_order_query_shows_non_draft_orders(+ staff_api_client, permission_manage_orders, orders+):query = """query OrdersQuery {orders(first: 10) {@@ -537,7 +545,117 @@ def test_order_query_draft_excluded(staff_api_client, permission_manage_orders,response = staff_api_client.post_graphql(query)edges = get_graphql_content(response)["data"]["orders"]["edges"]- assert len(edges) == Order.objects.confirmed().count()+ assert len(edges) == Order.objects.non_draft().count()+++ORDER_CONFIRM_MUTATION = """+ mutation orderConfirm($id: ID!) {+ orderConfirm(id: $id) {+ orderErrors {+ field+ code+ }+ order {+ status+ }+ }+ }+"""+++@patch("saleor.payment.gateway.capture")+def test_order_confirm(+ capture_mock,+ staff_api_client,+ order_unconfirmed,+ permission_manage_orders,+ payment_txn_preauth,+):+ payment_txn_preauth.order = order_unconfirmed+ payment_txn_preauth.save()+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ assert not OrderEvent.objects.exists()+ response = staff_api_client.post_graphql(+ ORDER_CONFIRM_MUTATION,+ {"id": graphene.Node.to_global_id("Order", order_unconfirmed.id)},+ )+ order_data = get_graphql_content(response)["data"]["orderConfirm"]["order"]++ assert order_data["status"] == OrderStatus.UNFULFILLED.upper()+ order_unconfirmed.refresh_from_db()+ assert order_unconfirmed.status == OrderStatus.UNFULFILLED+ assert OrderEvent.objects.count() == 3+ assert OrderEvent.objects.filter(+ order=order_unconfirmed,+ user=staff_api_client.user,+ type=order_events.OrderEvents.CONFIRMED,+ ).exists()+ assert OrderEvent.objects.filter(+ order=order_unconfirmed,+ user=staff_api_client.user,+ type=order_events.OrderEvents.EMAIL_SENT,+ parameters__email=order_unconfirmed.get_customer_email(),+ ).exists()+ assert OrderEvent.objects.filter(+ order=order_unconfirmed,+ user=staff_api_client.user,+ type=order_events.OrderEvents.PAYMENT_CAPTURED,+ parameters__amount=payment_txn_preauth.get_total().amount,+ ).exists()+ capture_mock.assert_called_once_with(payment_txn_preauth)+++def test_order_confirm_unfulfilled(staff_api_client, order, permission_manage_orders):+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(+ ORDER_CONFIRM_MUTATION, {"id": graphene.Node.to_global_id("Order", order.id)}+ )+ content = get_graphql_content(response)["data"]["orderConfirm"]+ errors = content["orderErrors"]++ order.refresh_from_db()+ assert order.status == OrderStatus.UNFULFILLED+ assert content["order"] is None+ assert len(errors) == 1+ assert errors[0]["field"] == "id"+ assert errors[0]["code"] == OrderErrorCode.INVALID.name+++@patch("saleor.payment.gateway.capture")+def test_order_confirm_wont_call_capture_for_non_active_payment(+ capture_mock,+ staff_api_client,+ order_unconfirmed,+ permission_manage_orders,+ payment_txn_preauth,+):+ payment_txn_preauth.order = order_unconfirmed+ payment_txn_preauth.is_active = False+ payment_txn_preauth.save()+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ assert not OrderEvent.objects.exists()+ response = staff_api_client.post_graphql(+ ORDER_CONFIRM_MUTATION,+ {"id": graphene.Node.to_global_id("Order", order_unconfirmed.id)},+ )+ order_data = get_graphql_content(response)["data"]["orderConfirm"]["order"]++ assert order_data["status"] == OrderStatus.UNFULFILLED.upper()+ order_unconfirmed.refresh_from_db()+ assert order_unconfirmed.status == OrderStatus.UNFULFILLED+ assert OrderEvent.objects.count() == 2+ assert OrderEvent.objects.filter(+ order=order_unconfirmed,+ user=staff_api_client.user,+ type=order_events.OrderEvents.CONFIRMED,+ ).exists()+ assert OrderEvent.objects.filter(+ order=order_unconfirmed,+ user=staff_api_client.user,+ type=order_events.OrderEvents.EMAIL_SENT,+ parameters__email=order_unconfirmed.get_customer_email(),+ ).exists()+ assert not capture_mock.calleddef test_orders_with_channel(@@ -580,7 +698,7 @@ def test_orders_without_channel(staff_api_client, permission_manage_orders, orderesponse = staff_api_client.post_graphql(query)edges = get_graphql_content(response)["data"]["orders"]["edges"]- assert len(edges) == Order.objects.confirmed().count()+ assert len(edges) == Order.objects.non_draft().count()def test_draft_order_query(staff_api_client, permission_manage_orders, orders):@@ -1972,15 +2090,24 @@ def test_draft_order_complete(data = content["data"]["draftOrderComplete"]["order"]order.refresh_from_db()assert data["status"] == order.status.upper()- draft_placed_event = OrderEvent.objects.get()for line in order:allocation = line.allocations.get()assert allocation.quantity_allocated == line.quantity_unfulfilled- assert draft_placed_event.user == staff_user- assert draft_placed_event.type == order_events.OrderEvents.PLACED_FROM_DRAFT- assert draft_placed_event.parameters == {}+ # ensure there are only 2 events with correct types+ event_params = {+ "user": staff_user,+ "type__in": [+ order_events.OrderEvents.PLACED_FROM_DRAFT,+ order_events.OrderEvents.CONFIRMED,+ ],+ "parameters": {},+ }+ matching_events = OrderEvent.objects.filter(**event_params)+ assert matching_events.count() == 2+ assert matching_events[0].type != matching_events[1].type+ assert not OrderEvent.objects.exclude(**event_params).exists()def test_draft_order_complete_with_inactive_channel(@@ -2031,13 +2158,22 @@ def test_draft_order_complete_product_without_inventory_tracking(order.refresh_from_db()assert data["status"] == order.status.upper()- draft_placed_event = OrderEvent.objects.get()assert not Allocation.objects.filter(order_line__order=order).exists()- assert draft_placed_event.user == staff_user- assert draft_placed_event.type == order_events.OrderEvents.PLACED_FROM_DRAFT- assert draft_placed_event.parameters == {}+ # ensure there are only 2 events with correct types+ event_params = {+ "user": staff_user,+ "type__in": [+ order_events.OrderEvents.PLACED_FROM_DRAFT,+ order_events.OrderEvents.CONFIRMED,+ ],+ "parameters": {},+ }+ matching_events = OrderEvent.objects.filter(**event_params)+ assert matching_events.count() == 2+ assert matching_events[0].type != matching_events[1].type+ assert not OrderEvent.objects.exclude(**event_params).exists()def test_draft_order_complete_out_of_stock_variant(@@ -3982,6 +4118,7 @@ def test_order_query_with_filter_payment_status("orders_filter, count, status",[({"status": "UNFULFILLED"}, 2, OrderStatus.UNFULFILLED),+ ({"status": "UNCONFIRMED"}, 1, OrderStatus.UNCONFIRMED),({"status": "PARTIALLY_FULFILLED"}, 1, OrderStatus.PARTIALLY_FULFILLED),({"status": "FULFILLED"}, 1, OrderStatus.FULFILLED),({"status": "CANCELED"}, 1, OrderStatus.CANCELED),diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 8deb6e6e16..5a90a9a8d5 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2555,6 +2555,7 @@ type Mutation {shopFetchTaxRates: ShopFetchTaxRatesshopSettingsTranslate(input: ShopSettingsTranslationInput!, languageCode: LanguageCodeEnum!): ShopSettingsTranslateshopAddressUpdate(input: AddressInput): ShopAddressUpdate+ orderSettingsUpdate(input: OrderSettingsUpdateInput!): OrderSettingsUpdateshippingMethodChannelListingUpdate(id: ID!, input: ShippingMethodChannelListingInput!): ShippingMethodChannelListingUpdateshippingPriceCreate(input: ShippingPriceInput!): ShippingPriceCreateshippingPriceDelete(id: ID!): ShippingPriceDelete@@ -2646,6 +2647,7 @@ type Mutation {orderAddNote(order: ID!, input: OrderAddNoteInput!): OrderAddNoteorderCancel(id: ID!): OrderCancelorderCapture(amount: PositiveDecimal!, id: ID!): OrderCapture+ orderConfirm(id: ID!): OrderConfirmorderFulfill(input: OrderFulfillInput!, order: ID): OrderFulfillorderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput!): FulfillmentCancelorderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTracking@@ -2885,6 +2887,12 @@ type OrderCapture {orderErrors: [OrderError!]!}+type OrderConfirm {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ order: Order+ orderErrors: [OrderError!]!+}+type OrderCountableConnection {pageInfo: PageInfo!edges: [OrderCountableEdge!]!@@ -2987,6 +2995,7 @@ type OrderEventOrderLineObject {enum OrderEventsEmailsEnum {PAYMENT_CONFIRMATION+ CONFIRMEDSHIPPING_CONFIRMATIONTRACKING_UPDATEDORDER_CONFIRMATION@@ -3008,6 +3017,7 @@ enum OrderEventsEnum {ORDER_FULLY_PAIDUPDATED_ADDRESSEMAIL_SENT+ CONFIRMEDPAYMENT_AUTHORIZEDPAYMENT_CAPTUREDEXTERNAL_SERVICE_NOTIFICATION@@ -3096,6 +3106,30 @@ type OrderRefund {orderErrors: [OrderError!]!}+type OrderSettings {+ automaticallyConfirmAllNewOrders: Boolean!+}++type OrderSettingsError {+ field: String+ message: String+ code: OrderSettingsErrorCode!+}++enum OrderSettingsErrorCode {+ INVALID+}++type OrderSettingsUpdate {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ orderSettings: OrderSettings+ orderSettingsErrors: [OrderSettingsError!]!+}++input OrderSettingsUpdateInput {+ automaticallyConfirmAllNewOrders: Boolean!+}+enum OrderSortField {NUMBERCREATION_DATE@@ -3111,6 +3145,7 @@ input OrderSortingInput {enum OrderStatus {DRAFT+ UNCONFIRMEDUNFULFILLEDPARTIALLY_FULFILLEDFULFILLED@@ -3121,6 +3156,7 @@ enum OrderStatusFilter {READY_TO_FULFILLREADY_TO_CAPTUREUNFULFILLED+ UNCONFIRMEDPARTIALLY_FULFILLEDFULFILLEDCANCELED@@ -4294,6 +4330,7 @@ type Query {stock(id: ID!): Stockstocks(filter: StockFilterInput, before: String, after: String, first: Int, last: Int): StockCountableConnectionshop: Shop!+ orderSettings: OrderSettingsshippingZone(id: ID!, channel: String): ShippingZoneshippingZones(channel: String, before: String, after: String, first: Int, last: Int): ShippingZoneCountableConnectiondigitalContent(id: ID!): DigitalContent@@ -5619,6 +5656,7 @@ type WebhookEvent {enum WebhookEventTypeEnum {ANY_EVENTSORDER_CREATED+ ORDER_CONFIRMEDORDER_FULLY_PAIDORDER_UPDATEDORDER_CANCELLED@@ -5637,6 +5675,7 @@ enum WebhookEventTypeEnum {enum WebhookSampleEventTypeEnum {ORDER_CREATED+ ORDER_CONFIRMEDORDER_FULLY_PAIDORDER_UPDATEDORDER_CANCELLEDdiff --git a/saleor/graphql/shop/error_codes.py b/saleor/graphql/shop/error_codes.pynew file mode 100644index 0000000000..4346a0620f--- /dev/null+++ b/saleor/graphql/shop/error_codes.py@@ -0,0 +1,5 @@+from enum import Enum+++class OrderSettingsErrorCode(Enum):+ INVALID = "invalid"diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.pyindex 89b23ae177..599c8a1825 100644--- a/saleor/graphql/shop/mutations.py+++ b/saleor/graphql/shop/mutations.py@@ -3,15 +3,15 @@ from django.core.exceptions import ValidationErrorfrom ...account import models as account_modelsfrom ...core.error_codes import ShopErrorCode-from ...core.permissions import SitePermissions+from ...core.permissions import OrderPermissions, SitePermissionsfrom ...core.utils.url import validate_storefront_urlfrom ...site import models as site_modelsfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..core.enums import WeightUnitsEnumfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation-from ..core.types.common import ShopError-from .types import AuthorizationKey, AuthorizationKeyType, Shop+from ..core.types.common import OrderSettingsError, ShopError+from .types import AuthorizationKey, AuthorizationKeyType, OrderSettings, Shopclass ShopSettingsInput(graphene.InputObjectType):@@ -366,3 +366,36 @@ class StaffNotificationRecipientDelete(ModelDeleteMutation):permissions = (SitePermissions.MANAGE_SETTINGS,)error_type_class = ShopErrorerror_type_field = "shop_errors"+++class OrderSettingsUpdateInput(graphene.InputObjectType):+ automatically_confirm_all_new_orders = graphene.Boolean(+ required=True,+ description="When disabled, all new orders from checkout "+ "will be marked as unconfirmed. When enabled orders from checkout will "+ "become unfulfilled immediately.",+ )+++class OrderSettingsUpdate(BaseMutation):+ order_settings = graphene.Field(OrderSettings, description="Order settings.")++ class Arguments:+ input = OrderSettingsUpdateInput(+ required=True, description="Fields required to update shop order settings."+ )++ class Meta:+ description = "Update shop order settings."+ permissions = (OrderPermissions.MANAGE_ORDERS,)+ error_type_class = OrderSettingsError+ error_type_field = "order_settings_errors"++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ instance = info.context.site.settings+ instance.automatically_confirm_all_new_orders = data["input"][+ "automatically_confirm_all_new_orders"+ ]+ instance.save(update_fields=["automatically_confirm_all_new_orders"])+ return OrderSettingsUpdate(order_settings=instance)diff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.pyindex 616a278c32..2e4d6f1dfc 100644--- a/saleor/graphql/shop/schema.py+++ b/saleor/graphql/shop/schema.py@@ -1,9 +1,12 @@import graphene+from ...core.permissions import OrderPermissions+from ..decorators import permission_requiredfrom ..translations.mutations import ShopSettingsTranslatefrom .mutations import (AuthorizationKeyAdd,AuthorizationKeyDelete,+ OrderSettingsUpdate,ShopAddressUpdate,ShopDomainUpdate,ShopFetchTaxRates,@@ -12,17 +15,24 @@ from .mutations import (StaffNotificationRecipientDelete,StaffNotificationRecipientUpdate,)-from .types import Shop+from .types import OrderSettings, Shopclass ShopQueries(graphene.ObjectType):shop = graphene.Field(Shop, description="Return information about the shop.", required=True,)+ order_settings = graphene.Field(+ OrderSettings, description="Order related settings from site settings."+ )def resolve_shop(self, _info):return Shop()+ @permission_required(OrderPermissions.MANAGE_ORDERS)+ def resolve_order_settings(self, info, *args, **_kwargs):+ return info.context.site.settings+class ShopMutations(graphene.ObjectType):authorization_key_add = AuthorizationKeyAdd.Field()@@ -37,3 +47,5 @@ class ShopMutations(graphene.ObjectType):shop_fetch_tax_rates = ShopFetchTaxRates.Field()shop_settings_translate = ShopSettingsTranslate.Field()shop_address_update = ShopAddressUpdate.Field()++ order_settings_update = OrderSettingsUpdate.Field()diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex 432ad928aa..1b4ee32deb 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -10,7 +10,7 @@ from ....core.permissions import get_permissions_codenamefrom ....site import AuthenticationBackendsfrom ....site.models import Sitefrom ...core.utils import str_to_enum-from ...tests.utils import get_graphql_content+from ...tests.utils import assert_no_permission, get_graphql_contentdef test_query_authorization_keys(@@ -1105,3 +1105,87 @@ def test_staff_notification_update_mutation_with_empty_email(}],}+++ORDER_SETTINGS_UPDATE_MUTATION = """+ mutation orderSettings($confirmOrders: Boolean!) {+ orderSettingsUpdate(+ input: { automaticallyConfirmAllNewOrders: $confirmOrders }+ ) {+ orderSettings {+ automaticallyConfirmAllNewOrders+ }+ }+ }+"""+++def test_order_settings_update_by_staff(+ staff_api_client, permission_manage_orders, site_settings+):+ assert site_settings.automatically_confirm_all_new_orders is True+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(+ ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False}+ )+ content = get_graphql_content(response)+ response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]+ assert response_settings["automaticallyConfirmAllNewOrders"] is False+ site_settings.refresh_from_db()+ assert site_settings.automatically_confirm_all_new_orders is False+++def test_order_settings_update_by_app(+ app_api_client, permission_manage_orders, site_settings+):+ assert site_settings.automatically_confirm_all_new_orders is True+ app_api_client.app.permissions.set([permission_manage_orders])+ response = app_api_client.post_graphql(+ ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False}+ )+ content = get_graphql_content(response)+ response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"]+ assert response_settings["automaticallyConfirmAllNewOrders"] is False+ site_settings.refresh_from_db()+ assert site_settings.automatically_confirm_all_new_orders is False+++def test_order_settings_update_by_user_without_permissions(+ user_api_client, permission_manage_orders, site_settings+):+ assert site_settings.automatically_confirm_all_new_orders is True+ response = user_api_client.post_graphql(+ ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False}+ )+ assert_no_permission(response)+ site_settings.refresh_from_db()+ assert site_settings.automatically_confirm_all_new_orders is True+++ORDER_SETTINGS_QUERY = """+ query orderSettings {+ orderSettings {+ automaticallyConfirmAllNewOrders+ }+ }+"""+++def test_order_settings_query_as_staff(+ staff_api_client, permission_manage_orders, site_settings+):+ assert site_settings.automatically_confirm_all_new_orders is True++ site_settings.automatically_confirm_all_new_orders = False+ site_settings.save(update_fields=["automatically_confirm_all_new_orders"])++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_SETTINGS_QUERY)+ content = get_graphql_content(response)++ assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is False+++def test_order_settings_query_as_user(user_api_client, site_settings):+ response = user_api_client.post_graphql(ORDER_SETTINGS_QUERY)+ assert_no_permission(response)diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex 6199db6675..53c4693e3b 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -15,6 +15,7 @@ from ...site import models as site_modelsfrom ..account.types import Address, StaffNotificationRecipientfrom ..channel import ChannelContextfrom ..checkout.types import PaymentGateway+from ..core.connection import CountableDjangoObjectTypefrom ..core.enums import WeightUnitsEnumfrom ..core.types.common import CountryDisplay, LanguageDisplay, Permissionfrom ..core.utils import str_to_enum@@ -64,6 +65,13 @@ class Geolocalization(graphene.ObjectType):description = "Represents customers's geolocalization data."+class OrderSettings(CountableDjangoObjectType):+ class Meta:+ only_fields = ["automatically_confirm_all_new_orders"]+ description = "Order related settings from site settings."+ model = site_models.SiteSettings++class Shop(graphene.ObjectType):available_payment_gateways = graphene.List(graphene.NonNull(PaymentGateway),diff --git a/saleor/order/__init__.py b/saleor/order/__init__.pyindex 47786b7ee7..07be3266dd 100644--- a/saleor/order/__init__.py+++ b/saleor/order/__init__.py@@ -1,5 +1,8 @@class OrderStatus:- DRAFT = "draft" # fully editable, not confirmed order created by staff users+ DRAFT = "draft" # fully editable, not finalized order created by staff users+ UNCONFIRMED = (+ "unconfirmed" # order created by customers when confirmation is required+ )UNFULFILLED = "unfulfilled" # order with no items marked as fulfilledPARTIALLY_FULFILLED = ("partially fulfilled" # order with some items marked as fulfilled@@ -9,6 +12,7 @@ class OrderStatus:CHOICES = [(DRAFT, "Draft"),+ (UNCONFIRMED, "Unconfirmed"),(UNFULFILLED, "Unfulfilled"),(PARTIALLY_FULFILLED, "Partially fulfilled"),(FULFILLED, "Fulfilled"),@@ -29,6 +33,7 @@ class FulfillmentStatus:class OrderEvents:"""The different order event types."""+ CONFIRMED = "confirmed"DRAFT_CREATED = "draft_created"DRAFT_ADDED_PRODUCTS = "draft_added_products"DRAFT_REMOVED_PRODUCTS = "draft_removed_products"@@ -79,6 +84,7 @@ class OrderEvents:(ORDER_FULLY_PAID, "The order was fully paid"),(UPDATED_ADDRESS, "The address from the placed order was updated"),(EMAIL_SENT, "The email was sent"),+ (CONFIRMED, "Order was confirmed"),(PAYMENT_AUTHORIZED, "The payment was authorized"),(PAYMENT_CAPTURED, "The payment was captured"),(EXTERNAL_SERVICE_NOTIFICATION, "Notification from external service"),@@ -101,6 +107,7 @@ class OrderEvents:class OrderEventsEmails:"""The different order emails event types."""+ CONFIRMED = "confirmed"PAYMENT = "payment_confirmation"SHIPPING = "shipping_confirmation"TRACKING_UPDATED = "tracking_updated"@@ -112,6 +119,7 @@ class OrderEventsEmails:CHOICES = [(PAYMENT, "The payment confirmation email was sent"),+ (CONFIRMED, "The order confirmed email was sent"),(SHIPPING, "The shipping confirmation email was sent"),(TRACKING_UPDATED, "The fulfillment tracking code email was sent"),(ORDER_CONFIRMATION, "The order placement confirmation email was sent"),diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 5832b5394c..712b5006f0 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -2,10 +2,12 @@ import loggingfrom decimal import Decimalfrom typing import TYPE_CHECKING, Dict, List, Optional+from django.contrib.sites.models import Sitefrom django.db import transactionfrom ..core import analyticsfrom ..core.exceptions import InsufficientStock+from ..order.emails import send_order_confirmedfrom ..payment import ChargeStatus, CustomPaymentChoices, PaymentError, TransactionKindfrom ..payment.models import Payment, Transactionfrom ..payment.utils import create_payment@@ -31,7 +33,6 @@ if TYPE_CHECKING:from ..warehouse.models import Warehousefrom .models import Order-logger = logging.getLogger(__name__)@@ -49,6 +50,23 @@ def order_created(order: "Order", user: "User", from_draft: bool = False):order_authorized(order=order, user=user, amount=payment.total, payment=payment)+ site_settings = Site.objects.get_current().settings+ if site_settings.automatically_confirm_all_new_orders:+ order_confirmed(order, user)+++def order_confirmed(+ order: "Order", user: "User", send_confirmation_email: bool = False+):+ """Order confirmed.++ Trigger event, plugin hooks and optionally confirmation email.+ """+ events.order_confirmed_event(order=order, user=user)+ manager = get_plugins_manager()+ manager.order_confirmed(order)+ if send_confirmation_email:+ send_order_confirmed.delay(order.pk, user.pk)def handle_fully_paid_order(order: "Order", user: Optional["User"] = None):diff --git a/saleor/order/emails.py b/saleor/order/emails.pyindex 6109008802..0caff4ee7f 100644--- a/saleor/order/emails.py+++ b/saleor/order/emails.py@@ -17,6 +17,7 @@ if TYPE_CHECKING:from ..account.models import User # noqa: F401CONFIRM_ORDER_TEMPLATE = "order/confirm_order"+CONFIRMED_ORDER_TEMPLATE = "order/confirmed_order"STAFF_CONFIRM_ORDER_TEMPLATE = "order/staff_confirm_order"CONFIRM_FULFILLMENT_TEMPLATE = "order/confirm_fulfillment"UPDATE_FULFILLMENT_TEMPLATE = "order/update_fulfillment"@@ -104,6 +105,19 @@ def send_order_confirmation(order_pk, redirect_url, user_pk=None):)+def send_order_confirmed(order_pk, user_pk):+ """Send email which tells customer that order has been confirmed."""+ email_data = collect_data_for_email(order_pk, CONFIRMED_ORDER_TEMPLATE)+ send_templated_mail(**email_data)+ events.email_sent_event(+ order=email_data["context"]["order"],+ user=None,+ user_pk=user_pk,+ email_type=events.OrderEventsEmails.CONFIRMED,+ )++@app.taskdef send_staff_order_confirmation(order_pk, redirect_url):"""Send order confirmation email."""diff --git a/saleor/order/events.py b/saleor/order/events.pyindex 7a680881da..4071098c04 100644--- a/saleor/order/events.py+++ b/saleor/order/events.py@@ -157,6 +157,14 @@ def order_created_event(return OrderEvent.objects.create(order=order, type=event_type, user=user)+def order_confirmed_event(+ *, order: Order, user: UserType, from_draft=False+) -> OrderEvent:+ if not _user_is_valid(user):+ user = None+ return OrderEvent.objects.create(order=order, type=OrderEvents.CONFIRMED, user=user)++def draft_order_oversold_items_event(*, order: Order, user: UserType, oversold_items: List[str]) -> OrderEvent:diff --git a/saleor/order/migrations/0092_order_unconfirmed.py b/saleor/order/migrations/0092_order_unconfirmed.pynew file mode 100644index 0000000000..91e2be9c1d--- /dev/null+++ b/saleor/order/migrations/0092_order_unconfirmed.py@@ -0,0 +1,66 @@+# Generated by Django 3.1.2 on 2020-11-23 10:55++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0091_order_redirect_url"),+ ]++ operations = [+ migrations.AlterField(+ model_name="order",+ name="status",+ field=models.CharField(+ choices=[+ ("draft", "Draft"),+ ("unconfirmed", "Unconfirmed"),+ ("unfulfilled", "Unfulfilled"),+ ("partially fulfilled", "Partially fulfilled"),+ ("fulfilled", "Fulfilled"),+ ("canceled", "Canceled"),+ ],+ default="unfulfilled",+ max_length=32,+ ),+ ),+ migrations.AlterField(+ model_name="orderevent",+ name="type",+ field=models.CharField(+ choices=[+ ("DRAFT_CREATED", "draft_created"),+ ("DRAFT_ADDED_PRODUCTS", "draft_added_products"),+ ("DRAFT_REMOVED_PRODUCTS", "draft_removed_products"),+ ("PLACED", "placed"),+ ("PLACED_FROM_DRAFT", "placed_from_draft"),+ ("OVERSOLD_ITEMS", "oversold_items"),+ ("CANCELED", "canceled"),+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),+ ("ORDER_FULLY_PAID", "order_fully_paid"),+ ("UPDATED_ADDRESS", "updated_address"),+ ("EMAIL_SENT", "email_sent"),+ ("CONFIRMED", "confirmed"),+ ("PAYMENT_AUTHORIZED", "payment_authorized"),+ ("PAYMENT_CAPTURED", "payment_captured"),+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),+ ("PAYMENT_REFUNDED", "payment_refunded"),+ ("PAYMENT_VOIDED", "payment_voided"),+ ("PAYMENT_FAILED", "payment_failed"),+ ("INVOICE_REQUESTED", "invoice_requested"),+ ("INVOICE_GENERATED", "invoice_generated"),+ ("INVOICE_UPDATED", "invoice_updated"),+ ("INVOICE_SENT", "invoice_sent"),+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),+ ("TRACKING_UPDATED", "tracking_updated"),+ ("NOTE_ADDED", "note_added"),+ ("OTHER", "other"),+ ],+ max_length=255,+ ),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 5dd734ab80..fe9a8b99c8 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -35,7 +35,11 @@ class OrderQueryset(models.QuerySet):return self.confirmed().filter(checkout_token=token).first()def confirmed(self):- """Return non-draft orders."""+ """Return orders that aren't draft or unconfirmed."""+ return self.exclude(status__in=[OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])++ def non_draft(self):+ """Return orders that aren't draft."""return self.exclude(status=OrderStatus.DRAFT)def drafts(self):@@ -66,6 +70,10 @@ class OrderQueryset(models.QuerySet):qs = qs.exclude(status={OrderStatus.DRAFT, OrderStatus.CANCELED})return qs.distinct()+ def ready_to_confirm(self):+ """Return unconfirmed_orders."""+ return self.filter(status=OrderStatus.UNCONFIRMED)+class Order(ModelWithMetadata):created = models.DateTimeField(default=now, editable=False)diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.pyindex 5a20e0f70a..f3ab3fed3c 100644--- a/saleor/payment/gateways/adyen/plugin.py+++ b/saleor/payment/gateways/adyen/plugin.py@@ -4,6 +4,7 @@ from urllib.parse import urlencodeimport Adyenfrom django.contrib.auth.hashers import make_password+from django.contrib.sites.models import Sitefrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse, HttpResponseNotFound@@ -275,6 +276,11 @@ class AdyenGatewayPlugin(BasePlugin):currencies=self.get_supported_currencies([]),)+ @property+ def order_auto_confirmation(self):+ site_settings = Site.objects.get_current().settings+ return site_settings.automatically_confirm_all_new_orders+@require_active_plugindef process_payment(self, payment_information: "PaymentData", previous_value@@ -322,7 +328,11 @@ class AdyenGatewayPlugin(BasePlugin):payment, action, result.message.get("details", []),)# If auto capture is enabled, let's make a capture the auth payment- elif self.config.auto_capture and result_code == AUTH_STATUS:+ elif (+ self.config.auto_capture+ and result_code == AUTH_STATUS+ and self.order_auto_confirmation+ ):kind = TransactionKind.CAPTUREresult = call_capture(payment_information=payment_information,@@ -375,7 +385,12 @@ class AdyenGatewayPlugin(BasePlugin):action_required = "action" in result.messageif result_code in PENDING_STATUSES:kind = TransactionKind.PENDING- elif is_success and config.auto_capture and not action_required:+ elif (+ is_success+ and config.auto_capture+ and self.order_auto_confirmation+ and not action_required+ ):# For enabled auto_capture on Saleor side we need to proceed an additional# actionkind = TransactionKind.CAPTUREdiff --git a/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_adyen_auto_capture_order_confirmation.yaml b/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_adyen_auto_capture_order_confirmation.yamlnew file mode 100644index 0000000000..fcead20271--- /dev/null+++ b/saleor/payment/gateways/adyen/tests/cassettes/test_process_payment_with_adyen_auto_capture_order_confirmation.yaml@@ -0,0 +1,48 @@+interactions:+- request:+ body: '{"amount": {"value": "123400", "currency": "USD"}, "reference": "UGF5bWVudDo3",+ "paymentMethod": {"paymentdata": ""}, "returnUrl": "http://127.0.0.1:3000/",+ "merchantAccount": "SaleorECOM", "applicationInfo": {"adyenLibrary": {"name":+ "adyen-python-api-library", "version": "3.0.0"}}}'+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ Content-Length:+ - '4444'+ Content-Type:+ - application/json+ User-Agent:+ - adyen-python-api-library/3.0.0+ x-api-key:+ - test_key+ method: POST+ uri: https://checkout-test.adyen.com/v49/payments+ response:+ body:+ string: '{"pspReference":"882595494831959A","resultCode":"Authorised","merchantReference":"UGF5bWVudDoz"}'+ headers:+ Connection:+ - Keep-Alive+ Content-Type:+ - application/json;charset=UTF-8+ Date:+ - Thu, 23 Jul 2020 09:00:31 GMT+ Keep-Alive:+ - timeout=15, max=100+ Server:+ - Apache+ Set-Cookie:+ - JSESSIONID=16B2B5BA678472CFD5D8FEE7C6EB1227.test103e; Path=/checkout; Secure;+ HttpOnly+ Transfer-Encoding:+ - chunked+ pspReference:+ - 881595494831497D+ status:+ code: 200+ message: '200'+version: 1diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.pyindex ccbc02b0e7..8888ea9b7c 100644--- a/saleor/payment/gateways/adyen/tests/test_plugin.py+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py@@ -94,8 +94,9 @@ def test_process_payment(payment_adyen_for_checkout, checkout_with_items, adyen_@pytest.mark.vcr[email protected]("saleor.payment.gateways.adyen.plugin.call_capture")def test_process_payment_with_adyen_auto_capture(- payment_adyen_for_checkout, checkout_with_items, adyen_plugin+ capture_mock, payment_adyen_for_checkout, checkout_with_items, adyen_plugin):payment_info = create_payment_information(payment_adyen_for_checkout,@@ -103,8 +104,11 @@ def test_process_payment_with_adyen_auto_capture()adyen_plugin = adyen_plugin(adyen_auto_capture=True)response = adyen_plugin.process_payment(payment_info, None)+ # ensure call_capture is not called+ assert not capture_mock.calledassert response.is_success is Trueassert response.action_required is False+ # kind should still be capture as Adyen had adyen_auto_capture set to Trueassert response.kind == TransactionKind.CAPTUREassert response.amount == Decimal("80.00")assert response.currency == checkout_with_items.currencydiff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex d8a1dfe31d..e1beb6bfa1 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -233,6 +233,14 @@ class BasePlugin:"""return NotImplemented+ def order_confirmed(self, order: "Order", previous_value: Any):+ """Trigger when order is confirmed by staff.++ Overwrite this method if you need to trigger specific logic after an order is+ confirmed.+ """+ return NotImplemented+def invoice_request(self,order: "Order",diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 86f23e8320..a4b05e7e2f 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -271,6 +271,10 @@ class PluginsManager(PaymentInterface):default_value = Nonereturn self.__run_method_on_plugins("order_created", default_value, order)+ def order_confirmed(self, order: "Order"):+ default_value = None+ return self.__run_method_on_plugins("order_confirmed", default_value, order)+def invoice_request(self, order: "Order", invoice: "Invoice", number: Optional[str]):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 5b94ac91c6..7dbb758cff 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -35,6 +35,12 @@ class WebhookPlugin(BasePlugin):order_data = generate_order_payload(order)trigger_webhooks_for_event.delay(WebhookEventType.ORDER_CREATED, order_data)+ def order_confirmed(self, order: "Order", previous_value: Any) -> Any:+ if not self.active:+ return previous_value+ order_data = generate_order_payload(order)+ trigger_webhooks_for_event.delay(WebhookEventType.ORDER_CONFIRMED, order_data)+def order_fully_paid(self, order: "Order", previous_value: Any) -> Any:if not self.active:return previous_valuediff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex fafbb2b105..fe936dd5d8 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -25,6 +25,7 @@ third_url = "http://www.example.com/third/"(WebhookEventType.ORDER_FULLY_PAID, 2, {first_url, third_url}),(WebhookEventType.ORDER_FULFILLED, 1, {third_url}),(WebhookEventType.ORDER_CANCELLED, 1, {third_url}),+ (WebhookEventType.ORDER_CONFIRMED, 1, {third_url}),(WebhookEventType.ORDER_UPDATED, 1, {third_url}),(WebhookEventType.ORDER_CREATED, 1, {third_url}),(WebhookEventType.CUSTOMER_CREATED, 0, set()),@@ -86,6 +87,18 @@ def test_order_created(mocked_webhook_trigger, settings, order_with_lines):)[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")+def test_order_confirmed(mocked_webhook_trigger, settings, order_with_lines):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ manager = get_plugins_manager()+ manager.order_confirmed(order_with_lines)++ expected_data = generate_order_payload(order_with_lines)+ mocked_webhook_trigger.assert_called_once_with(+ WebhookEventType.ORDER_CONFIRMED, expected_data+ )++@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")def test_customer_created(mocked_webhook_trigger, settings, customer_user):settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]diff --git a/saleor/site/migrations/0027_sitesettings_automatically_confirm_all_new_orders.py b/saleor/site/migrations/0027_sitesettings_automatically_confirm_all_new_orders.pynew file mode 100644index 0000000000..57c1d15434--- /dev/null+++ b/saleor/site/migrations/0027_sitesettings_automatically_confirm_all_new_orders.py@@ -0,0 +1,18 @@+# Generated by Django 3.1.2 on 2020-11-17 12:32++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("site", "0026_remove_sitesettings_homepage_collection"),+ ]++ operations = [+ migrations.AddField(+ model_name="sitesettings",+ name="automatically_confirm_all_new_orders",+ field=models.BooleanField(default=True),+ ),+ ]diff --git a/saleor/site/models.py b/saleor/site/models.pyindex 82a50dc354..c901cf03df 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -61,6 +61,7 @@ class SiteSettings(models.Model):)default_mail_sender_address = models.EmailField(blank=True, null=True)customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)+ automatically_confirm_all_new_orders = models.BooleanField(default=True)translated = TranslationProxy()class Meta:diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 69dd9459bd..52a0e2070d 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -555,6 +555,13 @@ def order(customer_user, channel_USD):)+def order_unconfirmed(order):+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ return order++@pytest.fixturedef admin_user(db):"""Return a Django admin user."""diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 363afdf8de..8137b86ee1 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -9,6 +9,7 @@ from ..core.permissions import (class WebhookEventType:ANY = "any_events"ORDER_CREATED = "order_created"+ ORDER_CONFIRMED = "order_confirmed"ORDER_FULLY_PAID = "order_fully_paid"ORDER_UPDATED = "order_updated"ORDER_CANCELLED = "order_cancelled"@@ -34,6 +35,7 @@ class WebhookEventType:DISPLAY_LABELS = {ANY: "Any events",ORDER_CREATED: "Order created",+ ORDER_CONFIRMED: "Order confirmed",ORDER_FULLY_PAID: "Order paid",ORDER_UPDATED: "Order updated",ORDER_CANCELLED: "Order cancelled",@@ -54,6 +56,7 @@ class WebhookEventType:CHOICES = [(ANY, DISPLAY_LABELS[ANY]),(ORDER_CREATED, DISPLAY_LABELS[ORDER_CREATED]),+ (ORDER_CONFIRMED, DISPLAY_LABELS[ORDER_CONFIRMED]),(ORDER_FULLY_PAID, DISPLAY_LABELS[ORDER_FULLY_PAID]),(ORDER_UPDATED, DISPLAY_LABELS[ORDER_UPDATED]),(ORDER_CANCELLED, DISPLAY_LABELS[ORDER_CANCELLED]),@@ -73,6 +76,7 @@ class WebhookEventType:PERMISSIONS = {ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,+ ORDER_CONFIRMED: OrderPermissions.MANAGE_ORDERS,ORDER_FULLY_PAID: OrderPermissions.MANAGE_ORDERS,ORDER_UPDATED: OrderPermissions.MANAGE_ORDERS,ORDER_CANCELLED: OrderPermissions.MANAGE_ORDERS,diff --git a/templates/templated_email/compiled/confirmed_order.html b/templates/templated_email/compiled/confirmed_order.htmlnew file mode 100644index 0000000000..e20ce5e41e--- /dev/null+++ b/templates/templated_email/compiled/confirmed_order.html@@ -0,0 +1,556 @@++ <!doctype html>+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">+ <head>+ <title>++ </title>+ <!--[if !mso]><!-- -->+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <!--<![endif]-->+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <style type="text/css">+ #outlook a { padding:0; }+ body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }+ table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }+ img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }+ p { display:block;margin:13px 0; }+ </style>+ <!--[if mso]>+ <xml>+ <o:OfficeDocumentSettings>+ <o:AllowPNG/>+ <o:PixelsPerInch>96</o:PixelsPerInch>+ </o:OfficeDocumentSettings>+ </xml>+ <![endif]-->+ <!--[if lte mso 11]>+ <style type="text/css">+ .mj-outlook-group-fix { width:100% !important; }+ </style>+ <![endif]-->++ <!--[if !mso]><!-->+ <link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css">+ <style type="text/css">+ @import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);+ </style>+ <!--<![endif]-->++++ <style type="text/css">+ @media only screen and (min-width:480px) {+ .mj-column-per-100 { width:100% !important; max-width: 100%; }+ }+ </style>+++ <style type="text/css">+++ </style>+ <style type="text/css">address {+ font-style: inherit;+ font-family: Ubuntu, Helvetica, Arial;+ }</style>++ </head>+ <body>+++ <div style>+ {% load i18n %}+ {% load i18n_address_tags %}{% load static %}++ <!--[if mso | IE]>+ <table+ align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"+ >+ <tr>+ <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">+ <![endif]-->+++ <div style="margin:0px auto;max-width:600px;">++ <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">+ <tbody>+ <tr>+ <td style="direction: ltr; font-size: 0px; padding: 20px 0; text-align: center;" align="center">+ <!--[if mso | IE]>+ <table role="presentation" border="0" cellpadding="0" cellspacing="0">++ <tr>++ <td+ class="" style="vertical-align:top;width:600px;"+ >+ <![endif]-->++ <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">++ <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">++ <tr>+ <td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">++ <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:16px;line-height:1;text-align:left;color:#000000;">{% trans "Hi!" context "Standard e-mail greeting" %}</div>++ </td>+ </tr>++ <tr>+ <td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">++ <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">{% if order_details_url %}+ {% blocktrans trimmed context "Order confirmed e-mail text with order details" %}+ Your order has been confirmed by staff. To see your order details please visit: <a href="{{ order_details_url }}">{{ order_details_url }}</a>+ {% endblocktrans %}+ {% else %}+ {% blocktrans trimmed context "Order confirmed e-mail text" %}+ Your order has been confirmed by staff. Below is the list of ordered products.+ {% endblocktrans %}+ {% endif %}</div>++ </td>+ </tr>++ </table>++ </div>++ <!--[if mso | IE]>+ </td>++ </tr>++ </table>+ <![endif]-->+ </td>+ </tr>+ </tbody>+ </table>++ </div>+++ <!--[if mso | IE]>+ </td>+ </tr>+ </table>+ <![endif]-->++ {% load display_translated_order_line_name from order_lines %}+ {% load price from taxed_prices %}+ {% load voucher %}++ <!--[if mso | IE]>+ <table+ align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"+ >+ <tr>+ <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">+ <![endif]-->+++ <div style="margin:0px auto;max-width:600px;">++ <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">+ <tbody>+ <tr>+ <td style="direction: ltr; font-size: 0px; padding: 20px 0; text-align: center;" align="center">+ <!--[if mso | IE]>+ <table role="presentation" border="0" cellpadding="0" cellspacing="0">++ <tr>++ <td+ class="" style="vertical-align:top;width:600px;"+ >+ <![endif]-->++ <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">++ <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">++ <tr>+ <td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">++ <table cellpadding="0" cellspacing="0" width="100%" border="0" style="color:#000000;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:22px;table-layout:auto;width:100%;border:none;">+ <tfoot>+ <tr>+ <td colspan="3" style="padding: 5px; text-align: right;" align="right">+ {% trans "Subtotal" context "E-mail order lines summary table" %}+ </td>+ <td style="padding: 5px; text-align: right;" align="right">+ {% price order.get_subtotal display_gross=order.display_gross_prices html=False %}+ </td>+ </tr>+ <tr>+ <td colspan="3" style="padding: 5px; text-align: right;" align="right">+ {% trans "Shipping" context "E-mail order lines summary table" %}+ </td>+ <td style="padding: 5px; text-align: right;" align="right">+ {% price order.shipping_price display_gross=order.display_gross_prices html=False %}+ </td>+ </tr>+ <tr>+ <td colspan="3" style="padding: 5px; text-align: right;" align="right">+ {% if order.display_gross_prices %}+ {% trans "Taxes (included)" context "E-mail order lines summary table" %}+ {% else %}+ {% trans "Taxes" context "E-mail order lines summary table" %}+ {% endif %}+ </td>+ <td style="padding: 5px; text-align: right;" align="right">+ {% price order.total.tax html=False %}+ </td>+ </tr>+ {% if order.discount_amount %}+ <tr>+ <td colspan="3" style="padding: 5px; text-align: right;" align="right">+ {% trans "Discount" context "E-mail order lines summary table" %}+ </td>+ <td style="padding: 5px; text-align: right;" align="right">+ {% discount_as_negative order.discount html=True %}+ </td>+ </tr>+ {% endif %}+ <tr>+ <td colspan="3" style="padding: 5px; text-align: right;" align="right">+ <strong>{% trans "Total" context "E-mail order lines summary table" %}</strong>+ </td>+ <td style="padding: 5px; text-align: right;" align="right">+ <strong>{% price order.total display_gross=order.display_gross_prices html=False %}</strong>+ </td>+ </tr>+ </tfoot>+ <thead class="table-header-row" style="border-bottom: 2px solid #000;">+ <tr>+ <th style="padding: 5px;">{% trans "Item" context "Ordered item name" %}</th>+ <th style="padding: 5px;">{% trans "Quantity" context "Quantity ordered of a product" %}</th>+ <th style="padding: 5px;">{% trans "Per unit" context "Unit price of a product" %}</th>+ <th style="padding: 5px;">{% trans "Subtotal" context "Ordered item subtotal (unit price * quantity)" %}</th>+ </tr>+ </thead>+ <tbody>+ {% for line in order %}+ <tr class="table-item-row" style="border-bottom: 1px solid #D3D1D0;">+ <td style="padding: 5px;">{% display_translated_order_line_name line %}</td>+ <td style="padding: 5px; text-align: right;" align="right">{{ line.quantity }}</td>+ <td style="padding: 5px; text-align: right;" align="right">+ {% price line.unit_price display_gross=order.display_gross_prices html=False %}+ </td>+ <td style="padding: 5px; text-align: right;" align="right">{% price line.get_total display_gross=order.display_gross_prices html=False %}</td>+ </tr>+ {% endfor %}+ </tbody>+ </table>++ </td>+ </tr>++ </table>++ </div>++ <!--[if mso | IE]>+ </td>++ </tr>++ </table>+ <![endif]-->+ </td>+ </tr>+ </tbody>+ </table>++ </div>+++ <!--[if mso | IE]>+ </td>+ </tr>+ </table>++ <table+ align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"+ >+ <tr>+ <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">+ <![endif]-->+++ <div style="margin:0px auto;max-width:600px;">++ <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">+ <tbody>+ <tr>+ <td style="direction: ltr; font-size: 0px; padding: 20px 0; text-align: center;" align="center">+ <!--[if mso | IE]>+ <table role="presentation" border="0" cellpadding="0" cellspacing="0">++ <tr>++ <td+ class="" style="vertical-align:top;width:600px;"+ >+ <![endif]-->++ <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">++ <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">++ <tr>+ <td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">++ <table cellpadding="0" cellspacing="0" width="100%" border="0" style="color:#000000;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:22px;table-layout:auto;width:100%;border:none;">+ <thead class="table-header-row" style="border-bottom: 2px solid #000;">+ <tr>+ <th style="padding: 5px;">{% trans "Billing address" context "Order confirmed e-mail billing address" %}</th>+ <th style="padding: 5px;">{% trans "Shipping address" context "Order confirmed e-mail shipping address" %}</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td class="address" style="padding: 5px;">+ {% if order.billing_address %}+ {% format_address order.billing_address %}+ {% else %}+ {% trans "No billing address" context "Order confirmed e-mail text" %}+ {% endif %}+ </td>+ <td css-class="address" style="padding: 5px;">+ {% if order.shipping_address %}+ {% format_address order.shipping_address %}+ {% else %}+ {% trans "No shipping required" context "Order confirmed e-mail text" %}+ {% endif %}+ </td>+ </tr>+ </tbody>+ </table>++ </td>+ </tr>++ </table>++ </div>++ <!--[if mso | IE]>+ </td>++ </tr>++ </table>+ <![endif]-->+ </td>+ </tr>+ </tbody>+ </table>++ </div>+++ <!--[if mso | IE]>+ </td>+ </tr>+ </table>++ <table+ align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"+ >+ <tr>+ <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">+ <![endif]-->+++ <div style="margin:0px auto;max-width:600px;">++ <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">+ <tbody>+ <tr>+ <td style="direction: ltr; font-size: 0px; padding: 20px 0; text-align: center;" align="center">+ <!--[if mso | IE]>+ <table role="presentation" border="0" cellpadding="0" cellspacing="0">++ <tr>++ <td+ class="" style="vertical-align:top;width:600px;"+ >+ <![endif]-->++ <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">++ <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">++ <tr>+ <td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">++ <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">{% blocktrans trimmed context "Base email text" %}+ This is an automatically generated e-mail, please do not reply.+ {% endblocktrans %}</div>++ </td>+ </tr>++ </table>++ </div>++ <!--[if mso | IE]>+ </td>++ </tr>++ </table>+ <![endif]-->+ </td>+ </tr>+ </tbody>+ </table>++ </div>+++ <!--[if mso | IE]>+ </td>+ </tr>+ </table>++ <table+ align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600"+ >+ <tr>+ <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">+ <![endif]-->+++ <div style="background:#F2F2F2;background-color:#F2F2F2;margin:0px auto;max-width:600px;">++ <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#F2F2F2;background-color:#F2F2F2;width:100%;">+ <tbody>+ <tr>+ <td style="direction: ltr; font-size: 0px; padding: 20px 0; text-align: center;" align="center">+ <!--[if mso | IE]>+ <table role="presentation" border="0" cellpadding="0" cellspacing="0">++ <tr>++ <td+ class="" style="vertical-align:top;width:600px;"+ >+ <![endif]-->++ <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">++ <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">++ <tr>+ <td align="center" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">++ <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:center;color:#000000;">{% blocktrans trimmed context "Base email footer" %}+ Sincerely, {{ site_name }}+ {% endblocktrans %}</div>++ </td>+ </tr>++ </table>++ </div>++ <!--[if mso | IE]>+ </td>++ </tr>++ </table>+ <![endif]-->+ </td>+ </tr>+ </tbody>+ </table>++ </div>+++ <!--[if mso | IE]>+ </td>+ </tr>+ </table>++ <table+ align="center" border="0" cellpadding="0" cellspacing="0" class="no-display-outlook" style="width:600px;" width="600"+ >+ <tr>+ <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;">+ <![endif]-->+++ <div class="no-display" style="display: none; margin: 0px auto; max-width: 600px;">++ <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;">+ <tbody>+ <tr>+ <td style="direction: ltr; font-size: 0px; padding: 20px 0; text-align: center;" align="center">+ <!--[if mso | IE]>+ <table role="presentation" border="0" cellpadding="0" cellspacing="0">++ <tr>++ <td+ class="" style="vertical-align:top;width:600px;"+ >+ <![endif]-->++ <div class="mj-column-per-100 mj-outlook-group-fix" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;">++ <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%">++ <tr>+ <td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">++ <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">{% if schema_markup %}+ <script type="application/ld+json">{{ schema_markup|safe }}</script>+ {% endif %}</div>++ </td>+ </tr>++ </table>++ </div>++ <!--[if mso | IE]>+ </td>++ </tr>++ </table>+ <![endif]-->+ </td>+ </tr>+ </tbody>+ </table>++ </div>+++ <!--[if mso | IE]>+ </td>+ </tr>+ </table>+ <![endif]-->+++ </div>++ </body>+ </html>+\ No newline at end of filediff --git a/templates/templated_email/order/confirmed_order.email b/templates/templated_email/order/confirmed_order.emailnew file mode 100644index 0000000000..8c957b561a--- /dev/null+++ b/templates/templated_email/order/confirmed_order.email@@ -0,0 +1,43 @@+{% load i18n %}+{% load price from taxed_prices %}+{% load voucher %}++{% block subject %}+ {% blocktrans trimmed context "Order confirmed e-mail subject" %}+ Order {{ order }} details+ {% endblocktrans %}+{% endblock %}++{% block plain %}+{% include 'templated_email/shared/_header.email' %}+{% blocktrans context "Order confirmed e-mail text" %}+Your order has been confirmed by staff. Below is the list of ordered products.+{% endblocktrans %}+{% if order_details_url %}+{% blocktrans context "Order confirmed e-mail payment details" %}+To see your order details please visit:+{{ order_details_url }}+{% endblocktrans %}+{% endif %}+{% for line in order %}+{{ line.quantity }} x {{ line }}, {% price line.get_total display_gross=order.display_gross_prices html=False %}+{% endfor %}+{% trans "Order summary" context "Order confirmed e-mail table header" %}:+{% trans "Subtotal" context "Order confirmed e-mail table header" %}: {% price order.get_subtotal display_gross=order.display_gross_prices html=False %}+{% trans "Shipping" context "Order confirmed e-mail table header" %}: {% price order.shipping_price display_gross=order.display_gross_prices html=False %}+{% if order.display_gross_prices %}{% trans "Taxes (included)" context "Order confirmed e-mail table header" %}{% else %}{% trans "Taxes" context "Order confirmed e-mail table header" %}{% endif %}: {% price order.total.tax html=False %}+{% if order.discount_amount %}{% trans "Discount:" context "Order confirmed e-mail table header" %} {% discount_as_negative order.discount %}{% endif %}+{% trans "Total" context "Order confirmed e-mail table header" %}: {% price order.total.gross html=False %}++{% trans "Billing address" context "Order confirmed e-mail billing address" %}+{% if order.billing_address %}{{ order.billing_address }}{% else %}{% trans "No billing address" context "Order confirmed e-mail text" %}{% endif %}++{% trans "Shipping address" context "Order confirmed e-mail shipping address" %}+{% if order.shipping_address %}{{ order.shipping_address }}{% else %}{% trans "No shipping required" context "Order confirmed e-mail text" %}{% endif %}++{% include 'templated_email/shared/_footer.email' %}+{% endblock %}++{% block html %}+{% include 'templated_email/compiled/confirmed_order.html' %}+{% endblock %}diff --git a/templates/templated_email/source/confirmed_order.mjml b/templates/templated_email/source/confirmed_order.mjmlnew file mode 100644index 0000000000..5ced846174--- /dev/null+++ b/templates/templated_email/source/confirmed_order.mjml@@ -0,0 +1,62 @@+<mjml>+ <mj-head>+ <mj-include path="./shared/styles.mjml" />+ </mj-head>+ <mj-body>+ <mj-raw>+ {% load i18n %}+ {% load i18n_address_tags %}+ </mj-raw>+ <mj-include path="./shared/header.mjml" />+ <mj-section>+ <mj-column>+ <mj-text font-size="16px">+ {% trans "Hi!" context "Standard e-mail greeting" %}+ </mj-text>+ <mj-text>+ {% if order_details_url %}+ {% blocktrans trimmed context "Order confirmed e-mail text with order details" %}+ Your order has been confirmed by staff. To see your order details please visit: <a href="{{ order_details_url }}">{{ order_details_url }}</a>+ {% endblocktrans %}+ {% else %}+ {% blocktrans trimmed context "Order confirmed e-mail text" %}+ Your order has been confirmed by staff. Below is the list of ordered products.+ {% endblocktrans %}+ {% endif %}+ </mj-text>+ </mj-column>+ </mj-section>+ <mj-include path="./partials/_order_lines.mjml" />+ <mj-section>+ <mj-column>+ <mj-table>+ <thead class="table-header-row">+ <tr>+ <th>{% trans "Billing address" context "Order confirmed e-mail billing address" %}</th>+ <th>{% trans "Shipping address" context "Order confirmed e-mail shipping address" %}</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td class="address">+ {% if order.billing_address %}+ {% format_address order.billing_address %}+ {% else %}+ {% trans "No billing address" context "Order confirmed e-mail text" %}+ {% endif %}+ </td>+ <td css-class="address">+ {% if order.shipping_address %}+ {% format_address order.shipping_address %}+ {% else %}+ {% trans "No shipping required" context "Order confirmed e-mail text" %}+ {% endif %}+ </td>+ </tr>+ </tbody>+ </mj-table>+ </mj-column>+ </mj-section>+ <mj-include path="./shared/footer.mjml" />+ </mj-body>+</mjml>