Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add TaxError handling in draft orders mutations
IKarbowiakf973fd7db46d
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 31b038597f..5e8b9f18c0 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -1,11 +1,12 @@import graphenefrom django.core.exceptions import ValidationError+from django.db import transactionfrom graphene.types import InputObjectTypefrom ....account.models import Userfrom ....core.exceptions import InsufficientStockfrom ....core.permissions import OrderPermissions-from ....core.taxes import zero_taxed_money+from ....core.taxes import TaxError, zero_taxed_moneyfrom ....order import OrderStatus, events, modelsfrom ....order.actions import order_createdfrom ....order.error_codes import OrderErrorCode@@ -173,6 +174,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):update_order_prices(instance, info.context.discounts)@classmethod+ @transaction.atomicdef save(cls, info, instance, cleaned_input):new_instance = not bool(instance.pk)@@ -182,15 +184,21 @@ class DraftOrderCreate(ModelMutation, I18nMixin):# Save any changes create/update the draftcls._commit_changes(info, instance, cleaned_input)- # Process any lines to add- cls._save_lines(- info,- instance,- cleaned_input.get("quantities"),- cleaned_input.get("variants"),- )+ try:+ # Process any lines to add+ cls._save_lines(+ info,+ instance,+ cleaned_input.get("quantities"),+ cleaned_input.get("variants"),+ )- cls._refresh_lines_unit_price(info, instance, cleaned_input, new_instance)+ cls._refresh_lines_unit_price(info, instance, cleaned_input, new_instance)+ except TaxError as tax_error:+ raise ValidationError(+ "Unable to calculate taxes - %s" % str(tax_error),+ code=OrderErrorCode.TAX_ERROR.value,+ )# Post-process the resultsrecalculate_order(instance)@@ -337,10 +345,16 @@ class DraftOrderLinesCreate(BaseMutation):)# Add the lines- lines = [- add_variant_to_draft_order(order, variant, quantity)- for quantity, variant in lines_to_add- ]+ try:+ lines = [+ add_variant_to_draft_order(order, variant, quantity)+ for quantity, variant in lines_to_add+ ]+ except TaxError as tax_error:+ raise ValidationError(+ "Unable to calculate taxes - %s" % str(tax_error),+ code=OrderErrorCode.TAX_ERROR.value,+ )# Create the eventevents.draft_order_added_products_event(diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 6812af7377..258e430027 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -11,7 +11,7 @@ from prices import Money, TaxedMoneyfrom ....account.models import CustomerEventfrom ....core.permissions import OrderPermissions-from ....core.taxes import zero_taxed_money+from ....core.taxes import TaxError, zero_taxed_moneyfrom ....order import OrderStatus, events as order_eventsfrom ....order.error_codes import OrderErrorCodefrom ....order.models import Order, OrderEvent@@ -558,6 +558,42 @@ def test_query_order_as_app(app_api_client, permission_manage_orders, order):assert order_data["token"] == order.token+DRAFT_ORDER_CREATE_MUTATION = """+mutation draftCreate(+ $user: ID, $discount: Decimal, $lines: [OrderLineCreateInput],+ $shippingAddress: AddressInput, $shippingMethod: ID, $voucher: ID,+ $customerNote: String) {+ draftOrderCreate(+ input: {user: $user, discount: $discount,+ lines: $lines, shippingAddress: $shippingAddress,+ shippingMethod: $shippingMethod, voucher: $voucher,+ customerNote: $customerNote}) {+ orderErrors {+ field+ message+ code+ }+ order {+ discount {+ amount+ }+ discountName+ lines {+ productName+ productSku+ quantity+ }+ status+ voucher {+ code+ }+ customerNote+ }+ }+ }+"""++def test_draft_order_create(staff_api_client,permission_manage_orders,@@ -570,40 +606,7 @@ def test_draft_order_create(graphql_address_data,):variant_0 = variant- query = """- mutation draftCreate(- $user: ID, $discount: Decimal, $lines: [OrderLineCreateInput],- $shippingAddress: AddressInput, $shippingMethod: ID, $voucher: ID,- $customerNote: String) {- draftOrderCreate(- input: {user: $user, discount: $discount,- lines: $lines, shippingAddress: $shippingAddress,- shippingMethod: $shippingMethod, voucher: $voucher,- customerNote: $customerNote}) {- errors {- field- message- }- order {- discount {- amount- }- discountName- lines {- productName- productSku- quantity- }- status- voucher {- code- }- customerNote- }- }- }- """-+ query = DRAFT_ORDER_CREATE_MUTATION# Ensure no events were created yetassert not OrderEvent.objects.exists()@@ -635,7 +638,7 @@ def test_draft_order_create(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- assert not content["data"]["draftOrderCreate"]["errors"]+ assert not content["data"]["draftOrderCreate"]["orderErrors"]data = content["data"]["draftOrderCreate"]["order"]assert data["status"] == OrderStatus.DRAFT.upper()assert data["voucher"]["code"] == voucher.code@@ -660,26 +663,95 @@ def test_draft_order_create(assert created_draft_event.parameters == {}+@patch("saleor.graphql.order.mutations.draft_orders.add_variant_to_draft_order")+def test_draft_order_create_tax_error(+ add_variant_to_draft_order_mock,+ staff_api_client,+ permission_manage_orders,+ staff_user,+ customer_user,+ product_without_shipping,+ shipping_method,+ variant,+ voucher,+ graphql_address_data,+):+ variant_0 = variant+ err_msg = "Test error"+ add_variant_to_draft_order_mock.side_effect = TaxError(err_msg)+ query = DRAFT_ORDER_CREATE_MUTATION+ # Ensure no events were created yet+ assert not OrderEvent.objects.exists()++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)+ variant_1 = product_without_shipping.variants.first()+ variant_1.quantity = 2+ variant_1.save()+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)+ discount = "10"+ customer_note = "Test note"+ variant_list = [+ {"variantId": variant_0_id, "quantity": 2},+ {"variantId": variant_1_id, "quantity": 1},+ ]+ shipping_address = graphql_address_data+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)+ variables = {+ "user": user_id,+ "discount": discount,+ "lines": variant_list,+ "shippingAddress": shipping_address,+ "shippingMethod": shipping_id,+ "voucher": voucher_id,+ "customerNote": customer_note,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["draftOrderCreate"]+ errors = data["orderErrors"]+ assert not data["order"]+ assert len(errors) == 1+ assert errors[0]["code"] == OrderErrorCode.TAX_ERROR.name+ assert errors[0]["message"] == f"Unable to calculate taxes - {err_msg}"++ order_count = Order.objects.all().count()+ assert order_count == 0+++DRAFT_ORDER_UPDATE_MUTATION = """+ mutation draftUpdate(+ $id: ID!, $voucher: ID!, $customerNote: String, $shippingAddress: AddressInput+ ) {+ draftOrderUpdate(id: $id,+ input: {+ voucher: $voucher,+ customerNote: $customerNote,+ shippingAddress: $shippingAddress,+ }) {+ orderErrors {+ field+ message+ code+ }+ order {+ userEmail+ }+ }+ }+"""++def test_draft_order_update(staff_api_client, permission_manage_orders, order_with_lines, voucher):order = order_with_linesassert not order.voucherassert not order.customer_note- query = """- mutation draftUpdate($id: ID!, $voucher: ID!, $customerNote: String) {- draftOrderUpdate(id: $id,- input: {voucher: $voucher, customerNote: $customerNote}) {- errors {- field- message- }- order {- userEmail- }- }- }- """+ query = DRAFT_ORDER_UPDATE_MUTATIONorder_id = graphene.Node.to_global_id("Order", order.id)voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)customer_note = "Test customer note"@@ -689,12 +761,51 @@ def test_draft_order_update()content = get_graphql_content(response)data = content["data"]["draftOrderUpdate"]- assert not data["errors"]+ assert not data["orderErrors"]order.refresh_from_db()assert order.voucherassert order.customer_note == customer_note+@patch("saleor.graphql.order.mutations.draft_orders.update_order_prices")+def test_draft_order_update_tax_error(+ update_order_prices_mock,+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ voucher,+ graphql_address_data,+):+ err_msg = "Test error"+ update_order_prices_mock.side_effect = TaxError(err_msg)+ order = order_with_lines+ assert not order.voucher+ assert not order.customer_note+ query = DRAFT_ORDER_UPDATE_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)+ customer_note = "Test customer note"+ variables = {+ "id": order_id,+ "voucher": voucher_id,+ "customerNote": customer_note,+ "shippingAddress": graphql_address_data,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["draftOrderUpdate"]+ errors = data["orderErrors"]+ assert len(errors) == 1+ assert errors[0]["code"] == OrderErrorCode.TAX_ERROR.name+ assert errors[0]["message"] == f"Unable to calculate taxes - {err_msg}"++ order.refresh_from_db()+ assert not order.voucher+ assert not order.customer_note++def test_draft_order_update_doing_nothing_generates_no_events(staff_api_client, permission_manage_orders, order_with_lines):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex e7eee51dc4..545979f28f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3001,6 +3001,7 @@ enum OrderErrorCode {REQUIREDSHIPPING_METHOD_NOT_APPLICABLESHIPPING_METHOD_REQUIRED+ TAX_ERRORUNIQUEVOID_INACTIVE_PAYMENTZERO_QUANTITYdiff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.pyindex e868994428..4e90b8f971 100644--- a/saleor/order/error_codes.py+++ b/saleor/order/error_codes.py@@ -21,6 +21,7 @@ class OrderErrorCode(Enum):REQUIRED = "required"SHIPPING_METHOD_NOT_APPLICABLE = "shipping_method_not_applicable"SHIPPING_METHOD_REQUIRED = "shipping_method_required"+ TAX_ERROR = "tax_error"UNIQUE = "unique"VOID_INACTIVE_PAYMENT = "void_inactive_payment"ZERO_QUANTITY = "zero_quantity"