Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' of github.com:mirumee/saleor into feature/unconfirmed-order-line-manipulation
Tomasz Szymanskid2c9cd8d5684
diff --cc saleor/graphql/order/mutations/draft_orders.pyindex 69502623be,ca7c59d9cb..eaa13ab94d--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@@ -216,10 -218,12 +216,10 @@@ class DraftOrderCreate(ModelMutation, Ilines = []for variant, quantity in zip(variants, quantities):lines.append((quantity, variant))- add_variant_to_order(instance, variant, quantity)- add_variant_to_draft_order(- instance, variant, quantity, info.context.plugins- )++ add_variant_to_order(instance, variant, quantity, info.context.plugins)# New event- events.draft_order_added_products_event(+ events.order_added_products_event(order=instance, user=info.context.user, order_lines=lines)@@@ -380,6 -384,190 +380,8 @@@ class DraftOrderComplete(BaseMutation)except InsufficientStock as exc:errors = prepare_insufficient_stock_order_validation_errors(exc)raise ValidationError({"lines": errors})- order_created(order, user=info.context.user, from_draft=True)+ order_created(+ order, user=info.context.user, manager=info.context.plugins, 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, info.context.plugins- )- 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 --cc saleor/graphql/order/mutations/orders.pyindex 788cc0c59d,d4f09aefed..16cba42aab--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@@ -580,220 -568,9 +601,225 @@@ class OrderConfirm(ModelMutation)order.status = OrderStatus.UNFULFILLEDorder.save(update_fields=["status"])payment = order.get_last_payment()+ manager = info.context.pluginsif 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)+ gateway.capture(payment, info.context.plugins)+ order_captured(order, info.context.user, payment.total, payment, manager)+ order_confirmed(order, info.context.user, manager, send_confirmation_email=True)return OrderConfirm(order=order)+++class EditableOrderValidationMixin:+ class Meta:+ abstract = True++ @classmethod+ def validate_order(cls, 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,+ )+ }+ )+++class OrderLinesCreate(EditableOrderValidationMixin, 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 validate_lines(cls, info, data):+ lines_to_add = []+ invalid_ids = []+ 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:+ lines_to_add.append((quantity, variant))+ else:+ invalid_ids.append(variant_id)+ if invalid_ids:+ raise ValidationError(+ {+ "quantity": ValidationError(+ "Variants quantity must be greater than 0.",+ code=OrderErrorCode.ZERO_QUANTITY,+ params={"variants": invalid_ids},+ ),+ }+ )+ return lines_to_add++ @staticmethod+ def validate_variants(order, variants):+ 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})++ @staticmethod- def add_lines_to_order(order, lines_to_add):++ def add_lines_to_order(order, lines_to_add, manager):+ try:+ return [+ add_variant_to_order(- order, variant, quantity, allocate_stock=order.is_unconfirmed()++ order,++ variant,++ quantity,++ manager,++ allocate_stock=order.is_unconfirmed(),+ )+ 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,+ )++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)+ cls.validate_order(order)+ lines_to_add = cls.validate_lines(info, data)+ variants = [line[1] for line in lines_to_add]+ cls.validate_variants(order, variants)+- lines = cls.add_lines_to_order(order, lines_to_add)++ lines = cls.add_lines_to_order(order, lines_to_add, info.context.plugins)++ # Create the products added event+ events.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(EditableOrderValidationMixin, 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+ cls.validate_order(line.order)++ db_id = line.id+ line_info = OrderLineData(+ line=line,+ quantity=line.quantity,+ variant=line.variant,+ warehouse_pk=line.allocations.first().stock.warehouse.pk,+ )+ delete_order_line(line_info)+ line.id = db_id++ # Create the removal event+ events.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(EditableOrderValidationMixin, 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)+ cls.validate_order(instance.order)++ 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):+ line_info = OrderLineData(+ line=instance,+ quantity=instance.quantity,+ variant=instance.variant,+ warehouse_pk=instance.allocations.first().stock.warehouse.pk,+ )+ try:+ change_order_line_quantity(+ info.context.user, line_info, instance.old_quantity, instance.quantity+ )+ except InsufficientStock:+ raise ValidationError(+ "Cannot set new quantity because of insufficient stock.",+ code=OrderErrorCode.INSUFFICIENT_STOCK,+ )+ recalculate_order(instance.order)++ @classmethod+ def success_response(cls, instance):+ response = super().success_response(instance)+ response.order = instance.order+ return responsediff --cc saleor/order/tests/test_emails.pyindex 5a745f8743,264a7a89b2..6981815b73--- a/saleor/order/tests/test_emails.py+++ b/saleor/order/tests/test_emails.py@@@ -7,7 -7,8 +7,8 @@@ from ...invoice import emails as invoicfrom ...invoice.models import Invoicefrom ...order import OrderEventsfrom ...order import emails as emails+ from ...plugins.manager import get_plugins_manager-from ..utils import add_variant_to_draft_order+from ..utils import add_variant_to_orderdef test_collect_data_for_order_confirmation_email(order):@@@ -144,7 -145,10 +145,10 @@@ def test_send_confirmation_emails_withoassert not order.lines.count()template = emails.CONFIRM_PAYMENT_TEMPLATE- add_variant_to_order(order, digital_content.product_variant, quantity=1)+ manager = get_plugins_manager()- add_variant_to_draft_order(++ add_variant_to_order(+ order, digital_content.product_variant, quantity=1, manager=manager+ )order.shipping_address = Noneorder.shipping_method = Noneorder.billing_address = None@@@ -178,7 -182,10 +182,10 @@@ def test_send_confirmation_emails_withoassert not order.lines.count()template = emails.CONFIRM_ORDER_TEMPLATE- add_variant_to_order(order, digital_content.product_variant, quantity=1)+ manager = get_plugins_manager()- add_variant_to_draft_order(++ add_variant_to_order(+ order, digital_content.product_variant, quantity=1, manager=manager+ )order.shipping_address = Noneorder.shipping_method = Noneorder.billing_address = Nonediff --cc saleor/order/tests/test_order.pyindex 8fbda14fa8,8939ac6602..7310a40099--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@@ -71,7 -71,8 +71,8 @@@ def test_add_variant_to_order_adds_linevariant = product.variants.get()lines_before = order.lines.count()settings.LANGUAGE_CODE = "fr"- add_variant_to_order(order, variant, 1)+ manager = get_plugins_manager()- add_variant_to_draft_order(order, variant, 1, manager)++ add_variant_to_order(order, variant, 1, manager)line = order.lines.last()assert order.lines.count() == lines_before + 1@@@ -94,7 -95,8 +95,8 @@@ def test_add_variant_to_order_adds_linelines_before = order.lines.count()settings.LANGUAGE_CODE = "fr"- add_variant_to_order(order, variant, 1)+ manager = get_plugins_manager()- add_variant_to_draft_order(order, variant, 1, manager)++ add_variant_to_order(order, variant, 1, manager)line = order.lines.last()assert order.lines.count() == lines_before + 1@@@ -112,8 -114,9 +114,9 @@@ def test_add_variant_to_order_not_allocstock = Stock.objects.get(product_variant=variant)stock_before = get_quantity_allocated_for_stock(stock)+ manager = get_plugins_manager()- add_variant_to_order(order_with_lines, variant, 1)- add_variant_to_draft_order(order_with_lines, variant, 1, manager)++ add_variant_to_order(order_with_lines, variant, 1, manager)stock.refresh_from_db()assert get_quantity_allocated_for_stock(stock) == stock_before@@@ -124,8 -127,9 +127,9 @@@ def test_add_variant_to_order_edits_linvariant = existing_line.variantlines_before = order_with_lines.lines.count()line_quantity_before = existing_line.quantity+ manager = get_plugins_manager()- add_variant_to_order(order_with_lines, variant, 1)- add_variant_to_draft_order(order_with_lines, variant, 1, manager)++ add_variant_to_order(order_with_lines, variant, 1, manager)existing_line.refresh_from_db()assert order_with_lines.lines.count() == lines_before@@@ -142,8 -146,9 +146,9 @@@ def test_add_variant_to_order_not_allocstock_before = get_quantity_allocated_for_stock(stock)quantity_before = existing_line.quantityquantity_unfulfilled_before = existing_line.quantity_unfulfilled+ manager = get_plugins_manager()- add_variant_to_order(order_with_lines, variant, 1)- add_variant_to_draft_order(order_with_lines, variant, 1, manager)++ add_variant_to_order(order_with_lines, variant, 1, manager)stock.refresh_from_db()existing_line.refresh_from_db()@@@ -565,7 -570,8 +570,8 @@@ def test_calculate_order_weight(order_wdef test_order_weight_add_more_variant(order_with_lines):variant = order_with_lines.lines.first().variant- add_variant_to_order(order_with_lines, variant, 2)+ manager = get_plugins_manager()- add_variant_to_draft_order(order_with_lines, variant, 2, manager)++ add_variant_to_order(order_with_lines, variant, 2, manager)order_with_lines.refresh_from_db()assert order_with_lines.weight == _calculate_order_weight_from_lines(order_with_lines@@@ -574,7 -580,8 +580,8 @@@def test_order_weight_add_new_variant(order_with_lines, product):variant = product.variants.first()- add_variant_to_order(order_with_lines, variant, 2)+ manager = get_plugins_manager()- add_variant_to_draft_order(order_with_lines, variant, 2, manager)++ add_variant_to_order(order_with_lines, variant, 2, manager)order_with_lines.refresh_from_db()assert order_with_lines.weight == _calculate_order_weight_from_lines(order_with_lines@@@ -600,7 -610,8 +607,8 @@@ def test_get_order_weight_non_existing_# Removing product should not affect order's weightorder = order_with_linesvariant = product.variants.first()- add_variant_to_order(order, variant, 1)+ manager = get_plugins_manager()- add_variant_to_draft_order(order, variant, 1, manager)++ add_variant_to_order(order, variant, 1, manager)old_weight = order.get_total_weight()product.delete()diff --cc saleor/order/utils.pyindex 6f22aa3118,e8bf90fd9d..3feb52ac2f--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@@ -16,16 -16,9 +16,15 @@@ from ..discount.models import NotApplicfrom ..discount.utils import get_products_voucher_discount, validate_voucher_in_orderfrom ..order import FulfillmentStatus, OrderLineData, OrderStatusfrom ..order.models import Order, OrderLine- from ..plugins.manager import get_plugins_managerfrom ..product.utils.digital_products import get_default_digital_content_settingsfrom ..shipping.models import ShippingMethod-from ..warehouse.management import deallocate_stock, increase_stock+from ..warehouse.management import (+ deallocate_stock,+ decrease_allocations,+ get_order_lines_with_track_inventory,+ increase_allocations,+ increase_stock,+)from ..warehouse.models import Warehousefrom . import events@@@ -295,9 -290,7 +296,9 @@@ def update_order_status(order)@transaction.atomic-def add_variant_to_draft_order(order, variant, quantity, manager, discounts=None):+def add_variant_to_order(- order, variant, quantity, discounts=None, allocate_stock=False++ order, variant, quantity, manager, discounts=None, allocate_stock=False+):"""Add total_quantity of variant to order.Returns an order line the variant was added to.@@@ -339,10 -332,8 +340,9 @@@unit_price = manager.calculate_order_line_unit(order, line, variant, product)line.unit_price = unit_priceline.tax_rate = manager.get_order_line_tax_rate(- order, product, None, unit_price+ order, product, variant, None, unit_price)+ line.total_price = unit_price * quantityline.save(update_fields=["currency",