Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move and refactor DraftOrderLine* -> OrderLine* CRUD to orders
Tomasz Szymański68d728d22ea5
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 0fd1da9120..ca0c7c0e73 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -13,8 +13,6 @@ from ....order.actions import order_createdfrom ....order.error_codes import OrderErrorCodefrom ....order.utils import (add_variant_to_draft_order,- change_order_line_quantity,- delete_order_line,get_order_country,recalculate_order,update_order_prices,@@ -27,7 +25,7 @@ from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types.common import OrderErrorfrom ...product.types import ProductVariant-from ..types import Order, OrderLine+from ..types import Orderfrom ..utils import (validate_draft_order,validate_product_is_published_in_channel,@@ -377,183 +375,3 @@ class DraftOrderComplete(BaseMutation):order_created(order, user=info.context.user, from_draft=True)return DraftOrderComplete(order=order)---class DraftOrderLinesCreate(BaseMutation):- order = graphene.Field(Order, description="A related draft order.")- order_lines = graphene.List(- graphene.NonNull(OrderLine), description="List of newly added order lines."- )-- class Arguments:- id = graphene.ID(- required=True, description="ID of the draft order to add the lines to."- )- input = graphene.List(- OrderLineCreateInput,- required=True,- description="Fields required to add order lines.",- )-- class Meta:- description = "Create order lines for a draft order."- permissions = (OrderPermissions.MANAGE_ORDERS,)- error_type_class = OrderError- error_type_field = "order_errors"-- @classmethod- def perform_mutation(cls, _root, info, **data):- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)- if order.status != OrderStatus.DRAFT:- raise ValidationError(- {- "id": ValidationError(- "Only draft orders can be edited.",- code=OrderErrorCode.NOT_EDITABLE,- )- }- )-- lines_to_add = []- for input_line in data.get("input"):- variant_id = input_line["variant_id"]- variant = cls.get_node_or_error(- info, variant_id, "variant_id", only_type=ProductVariant- )- quantity = input_line["quantity"]- if quantity > 0:- if variant:- lines_to_add.append((quantity, variant))- else:- raise ValidationError(- {- "quantity": ValidationError(- "Ensure this value is greater than 0.",- code=OrderErrorCode.ZERO_QUANTITY,- )- }- )- variants = [line[1] for line in lines_to_add]- try:- channel = order.channel- validate_product_is_published_in_channel(variants, channel)- validate_variant_channel_listings(variants, channel)- except ValidationError as error:- raise ValidationError({"input": error})- # Add the lines- 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 event- events.draft_order_added_products_event(- order=order, user=info.context.user, order_lines=lines_to_add- )-- recalculate_order(order)- return DraftOrderLinesCreate(order=order, order_lines=lines)---class DraftOrderLineDelete(BaseMutation):- order = graphene.Field(Order, description="A related draft order.")- order_line = graphene.Field(- OrderLine, description="An order line that was deleted."- )-- class Arguments:- id = graphene.ID(description="ID of the order line to delete.", required=True)-- class Meta:- description = "Deletes an order line from a draft order."- permissions = (OrderPermissions.MANAGE_ORDERS,)- error_type_class = OrderError- error_type_field = "order_errors"-- @classmethod- def perform_mutation(cls, _root, info, id):- line = cls.get_node_or_error(info, id, only_type=OrderLine)- order = line.order- if order.status != OrderStatus.DRAFT:- raise ValidationError(- {- "id": ValidationError(- "Only draft orders can be edited.",- code=OrderErrorCode.NOT_EDITABLE,- )- }- )-- db_id = line.id- delete_order_line(line)- line.id = db_id-- # Create the removal event- events.draft_order_removed_products_event(- order=order, user=info.context.user, order_lines=[(line.quantity, line)]- )-- recalculate_order(order)- return DraftOrderLineDelete(order=order, order_line=line)---class DraftOrderLineUpdate(ModelMutation):- order = graphene.Field(Order, description="A related draft order.")-- class Arguments:- id = graphene.ID(description="ID of the order line to update.", required=True)- input = OrderLineInput(- required=True, description="Fields required to update an order line."- )-- class Meta:- description = "Updates an order line of a draft order."- model = models.OrderLine- permissions = (OrderPermissions.MANAGE_ORDERS,)- error_type_class = OrderError- error_type_field = "order_errors"-- @classmethod- def clean_input(cls, info, instance, data):- instance.old_quantity = instance.quantity- cleaned_input = super().clean_input(info, instance, data)- if instance.order.status != OrderStatus.DRAFT:- raise ValidationError(- {- "id": ValidationError(- "Only draft orders can be edited.",- code=OrderErrorCode.NOT_EDITABLE,- )- }- )-- quantity = data["quantity"]- if quantity <= 0:- raise ValidationError(- {- "quantity": ValidationError(- "Ensure this value is greater than 0.",- code=OrderErrorCode.ZERO_QUANTITY,- )- }- )- return cleaned_input-- @classmethod- def save(cls, info, instance, cleaned_input):- change_order_line_quantity(- info.context.user, instance, instance.old_quantity, instance.quantity- )- recalculate_order(instance.order)-- @classmethod- def success_response(cls, instance):- response = super().success_response(instance)- response.order = instance.order- return responsediff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 45ea347bde..51107ca089 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -4,7 +4,7 @@ from django.db import transactionfrom ....account.models import Userfrom ....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 (cancel_order,@@ -17,7 +17,14 @@ from ....order.actions import (order_voided,)from ....order.error_codes import OrderErrorCode-from ....order.utils import get_valid_shipping_methods_for_order, update_order_prices+from ....order.utils import (+ add_variant_to_draft_order,+ change_order_line_quantity,+ delete_order_line,+ get_valid_shipping_methods_for_order,+ recalculate_order,+ update_order_prices,+)from ....payment import CustomPaymentChoices, PaymentError, TransactionKind, gatewayfrom ....shipping import models as shipping_modelsfrom ...account.types import AddressInput@@ -25,9 +32,20 @@ from ...core.mutations import BaseMutation, ModelMutationfrom ...core.scalars import PositiveDecimalfrom ...core.types.common import OrderErrorfrom ...core.utils import validate_required_string_field-from ...order.mutations.draft_orders import DraftOrderCreate-from ...order.types import Order, OrderEvent+from ...order.mutations.draft_orders import (+ DraftOrderCreate,+ OrderLineCreateInput,+ OrderLineInput,+)+from ...product.types import ProductVariantfrom ...shipping.types import ShippingMethod+from ..types import Order, OrderEvent, OrderLine+from ..utils import (+ validate_product_is_published_in_channel,+ validate_variant_channel_listings,+)++ORDER_EDITABLE_STATUS = (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED)def clean_order_update_shipping(order, method):@@ -541,3 +559,183 @@ class OrderConfirm(ModelMutation):order_captured(order, info.context.user, payment.total, payment)order_confirmed(order, info.context.user, send_confirmation_email=True)return OrderConfirm(order=order)+++class OrderLinesCreate(BaseMutation):+ order = graphene.Field(Order, description="Related order.")+ order_lines = graphene.List(+ graphene.NonNull(OrderLine), description="List of added order lines."+ )++ class Arguments:+ id = graphene.ID(+ required=True, description="ID of the order to add the lines to."+ )+ input = graphene.List(+ OrderLineCreateInput,+ required=True,+ description="Fields required to add order lines.",+ )++ class Meta:+ description = "Create order lines for an order."+ permissions = (OrderPermissions.MANAGE_ORDERS,)+ error_type_class = OrderError+ error_type_field = "order_errors"++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)+ if order.status not in ORDER_EDITABLE_STATUS:+ raise ValidationError(+ {+ "id": ValidationError(+ "Only draft and unconfirmed orders can be edited.",+ code=OrderErrorCode.NOT_EDITABLE,+ )+ }+ )++ lines_to_add = []+ for input_line in data.get("input"):+ variant_id = input_line["variant_id"]+ variant = cls.get_node_or_error(+ info, variant_id, "variant_id", only_type=ProductVariant+ )+ quantity = input_line["quantity"]+ if quantity > 0:+ if variant:+ lines_to_add.append((quantity, variant))+ else:+ raise ValidationError(+ {+ "quantity": ValidationError(+ "Ensure this value is greater than 0.",+ code=OrderErrorCode.ZERO_QUANTITY,+ )+ }+ )+ variants = [line[1] for line in lines_to_add]+ try:+ channel = order.channel+ validate_product_is_published_in_channel(variants, channel)+ validate_variant_channel_listings(variants, channel)+ except ValidationError as error:+ raise ValidationError({"input": error})+ # Add the lines+ 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 event+ events.draft_order_added_products_event(+ order=order, user=info.context.user, order_lines=lines_to_add+ )++ recalculate_order(order)+ return OrderLinesCreate(order=order, order_lines=lines)+++class OrderLineDelete(BaseMutation):+ order = graphene.Field(Order, description="A related order.")+ order_line = graphene.Field(+ OrderLine, description="An order line that was deleted."+ )++ class Arguments:+ id = graphene.ID(description="ID of the order line to delete.", required=True)++ class Meta:+ description = "Deletes an order line from an order."+ permissions = (OrderPermissions.MANAGE_ORDERS,)+ error_type_class = OrderError+ error_type_field = "order_errors"++ @classmethod+ def perform_mutation(cls, _root, info, id):+ line = cls.get_node_or_error(info, id, only_type=OrderLine)+ order = line.order+ if order.status not in ORDER_EDITABLE_STATUS:+ raise ValidationError(+ {+ "id": ValidationError(+ "Only draft and unconfirmed orders can be edited.",+ code=OrderErrorCode.NOT_EDITABLE,+ )+ }+ )++ db_id = line.id+ delete_order_line(line)+ line.id = db_id++ # Create the removal event+ events.draft_order_removed_products_event(+ order=order, user=info.context.user, order_lines=[(line.quantity, line)]+ )++ recalculate_order(order)+ return OrderLineDelete(order=order, order_line=line)+++class OrderLineUpdate(ModelMutation):+ order = graphene.Field(Order, description="Related order.")++ class Arguments:+ id = graphene.ID(description="ID of the order line to update.", required=True)+ input = OrderLineInput(+ required=True, description="Fields required to update an order line."+ )++ class Meta:+ description = "Updates an order line of an order."+ model = models.OrderLine+ permissions = (OrderPermissions.MANAGE_ORDERS,)+ error_type_class = OrderError+ error_type_field = "order_errors"++ @classmethod+ def clean_input(cls, info, instance, data):+ instance.old_quantity = instance.quantity+ cleaned_input = super().clean_input(info, instance, data)+ if instance.order.status not in ORDER_EDITABLE_STATUS:+ raise ValidationError(+ {+ "id": ValidationError(+ "Only draft and unconfirmed orders can be edited.",+ code=OrderErrorCode.NOT_EDITABLE,+ )+ }+ )++ quantity = data["quantity"]+ if quantity <= 0:+ raise ValidationError(+ {+ "quantity": ValidationError(+ "Ensure this value is greater than 0.",+ code=OrderErrorCode.ZERO_QUANTITY,+ )+ }+ )+ return cleaned_input++ @classmethod+ def save(cls, info, instance, cleaned_input):+ change_order_line_quantity(+ info.context.user, instance, instance.old_quantity, instance.quantity+ )+ recalculate_order(instance.order)++ @classmethod+ def success_response(cls, instance):+ response = super().success_response(instance)+ response.order = instance.order+ return responsediff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex 662d3f27ee..d204dbc0bf 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -14,9 +14,6 @@ from .mutations.draft_orders import (DraftOrderComplete,DraftOrderCreate,DraftOrderDelete,- DraftOrderLineDelete,- DraftOrderLinesCreate,- DraftOrderLineUpdate,DraftOrderUpdate,)from .mutations.fulfillments import (@@ -30,6 +27,9 @@ from .mutations.orders import (OrderCancel,OrderCapture,OrderConfirm,+ OrderLineDelete,+ OrderLinesCreate,+ OrderLineUpdate,OrderMarkAsPaid,OrderRefund,OrderUpdate,@@ -152,9 +152,6 @@ class OrderMutations(graphene.ObjectType):draft_order_delete = DraftOrderDelete.Field()draft_order_bulk_delete = DraftOrderBulkDelete.Field()draft_order_lines_bulk_delete = DraftOrderLinesBulkDelete.Field()- draft_order_lines_create = DraftOrderLinesCreate.Field()- draft_order_line_delete = DraftOrderLineDelete.Field()- draft_order_line_update = DraftOrderLineUpdate.Field()draft_order_update = DraftOrderUpdate.Field()order_add_note = OrderAddNote.Field()@@ -167,6 +164,9 @@ class OrderMutations(graphene.ObjectType):order_fulfillment_update_tracking = FulfillmentUpdateTracking.Field()order_fulfillment_refund_products = FulfillmentRefundProducts.Field()+ order_lines_create = OrderLinesCreate.Field()+ order_line_delete = OrderLineDelete.Field()+ order_line_update = OrderLineUpdate.Field()order_mark_as_paid = OrderMarkAsPaid.Field()order_refund = OrderRefund.Field()order_update = OrderUpdate.Field()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex d6f41bf387..76391549ff 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1809,33 +1809,12 @@ input DraftOrderInput {redirectUrl: String}-type DraftOrderLineDelete {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- order: Order- orderLine: OrderLine- orderErrors: [OrderError!]!-}--type DraftOrderLineUpdate {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- order: Order- orderErrors: [OrderError!]!- orderLine: OrderLine-}-type DraftOrderLinesBulkDelete {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")count: Int!orderErrors: [OrderError!]!}-type DraftOrderLinesCreate {- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")- order: Order- orderLines: [OrderLine!]- orderErrors: [OrderError!]!-}-type DraftOrderUpdate {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")orderErrors: [OrderError!]!@@ -2647,9 +2626,6 @@ type Mutation {draftOrderDelete(id: ID!): DraftOrderDeletedraftOrderBulkDelete(ids: [ID]!): DraftOrderBulkDeletedraftOrderLinesBulkDelete(ids: [ID]!): DraftOrderLinesBulkDelete- draftOrderLinesCreate(id: ID!, input: [OrderLineCreateInput]!): DraftOrderLinesCreate- draftOrderLineDelete(id: ID!): DraftOrderLineDelete- draftOrderLineUpdate(id: ID!, input: OrderLineInput!): DraftOrderLineUpdatedraftOrderUpdate(id: ID!, input: DraftOrderInput!): DraftOrderUpdateorderAddNote(order: ID!, input: OrderAddNoteInput!): OrderAddNoteorderCancel(id: ID!): OrderCancel@@ -2659,6 +2635,9 @@ type Mutation {orderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput!): FulfillmentCancelorderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTrackingorderFulfillmentRefundProducts(input: OrderRefundProductsInput!, order: ID!): FulfillmentRefundProducts+ orderLinesCreate(id: ID!, input: [OrderLineCreateInput]!): OrderLinesCreate+ orderLineDelete(id: ID!): OrderLineDelete+ orderLineUpdate(id: ID!, input: OrderLineInput!): OrderLineUpdateorderMarkAsPaid(id: ID!, transactionReference: String): OrderMarkAsPaidorderRefund(amount: PositiveDecimal!, id: ID!): OrderRefundorderUpdate(id: ID!, input: OrderUpdateInput!): OrderUpdate@@ -3105,10 +3084,31 @@ input OrderLineCreateInput {variantId: ID!}+type OrderLineDelete {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ order: Order+ orderLine: OrderLine+ orderErrors: [OrderError!]!+}+input OrderLineInput {quantity: Int!}+type OrderLineUpdate {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ order: Order+ orderErrors: [OrderError!]!+ orderLine: OrderLine+}++type OrderLinesCreate {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ order: Order+ orderLines: [OrderLine!]+ orderErrors: [OrderError!]!+}+type OrderMarkAsPaid {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")order: Order