Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge branch 'master' of github.com:mirumee/saleor into SALEOR-2645-recalculate-draft-order-total
Damian W245e60e014e8
diff --cc saleor/graphql/order/mutations/draft_orders.pyindex f7e50ec001,d975b5714f..b9e8e1c492--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@@ -227,12 -216,10 +225,12 @@@ class DraftOrderCreate(ModelMutation, Ilines = []for variant, quantity in zip(variants, quantities):lines.append((quantity, variant))- add_variant_to_draft_order(- add_variant_to_order(instance, variant, quantity, info.context.plugins)++ add_variant_to_order(+ instance, variant, quantity, info.context.user, 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)diff --cc saleor/graphql/order/mutations/orders.pyindex d4f09aefed,f20b501693..d1cc672b48--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@@ -574,3 -607,229 +607,232 @@@ class OrderConfirm(ModelMutation)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, manager):++ def add_lines_to_order(order, lines_to_add, user, manager):+ try:+ return [+ add_variant_to_order(+ order,+ variant,+ quantity,++ user,+ 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, info.context.plugins)++ lines = cls.add_lines_to_order(++ order, lines_to_add, info.context.user, 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+ warehouse_pk = (+ line.allocations.first().stock.warehouse.pk+ if order.is_unconfirmed()+ else None+ )+ line_info = OrderLineData(+ line=line,+ quantity=line.quantity,+ variant=line.variant,+ warehouse_pk=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):+ warehouse_pk = (+ instance.allocations.first().stock.warehouse.pk+ if instance.order.is_unconfirmed()+ else None+ )+ line_info = OrderLineData(+ line=instance,+ quantity=instance.quantity,+ variant=instance.variant,+ warehouse_pk=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_notifications.pyindex d4f767878c,eea8e9863b..a8a5c39324--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@@ -266,13 -265,10 +266,13 @@@ def test_send_confirmation_emails_withopayment_dummy,):order = payment_dummy.order- manager = get_plugins_manager()- line = add_variant_to_draft_order(+ line = add_variant_to_order(- order, digital_content.product_variant, quantity=1, manager=manager+ order,+ digital_content.product_variant,+ quantity=1,+ user=info.context.user,+ manager=info.context.plugins,)DigitalContentUrl.objects.create(content=digital_content, line=line)@@@ -308,13 -304,10 +308,13 @@@ def test_send_confirmation_emails_witho):assert not order.lines.count()- manager = get_plugins_manager()- line = add_variant_to_draft_order(+ line = add_variant_to_order(- order, digital_content.product_variant, quantity=1, manager=manager+ order,+ digital_content.product_variant,+ quantity=1,+ user=info.context.user,+ manager=info.context.plugins,)DigitalContentUrl.objects.create(content=digital_content, line=line)diff --cc saleor/order/tests/test_order.pyindex f406ae6366,90e448693e..4c743e0500--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@@ -75,16 -75,15 +75,14 @@@ def test_order_get_subtotal(order_with_assert order_with_lines.get_subtotal() == target_subtotal- def test_add_variant_to_draft_order_adds_line_for_new_variant(+ def test_add_variant_to_order_adds_line_for_new_variant(- order_with_lines, product, product_translation_fr, settings+ order_with_lines, product, product_translation_fr, settings, info):order = order_with_linesvariant = product.variants.get()lines_before = order.lines.count()settings.LANGUAGE_CODE = "fr"- add_variant_to_draft_order(- order, variant, 1, info.context.user, info.context.plugins- )- manager = get_plugins_manager()- add_variant_to_order(order, variant, 1, manager)++ add_variant_to_order(order, variant, 1, info.context.user, info.context.plugins)line = order.lines.last()assert order.lines.count() == lines_before + 1@@@ -108,7 -107,7 +106,8 @@@ def test_add_variant_to_draft_order_addcalculate_order_line_unit=Mock(return_value=price),get_order_line_tax_rate=Mock(return_value=0.25),)- add_variant_to_draft_order(order, variant, 1, info.context.user, manager)- add_variant_to_order(order, variant, 1, manager)++++ add_variant_to_order(order, variant, 1, info.context.user, manager)line = order.lines.last()assert order.lines.count() == lines_before + 1@@@ -132,9 -131,8 +131,7 @@@ def test_add_variant_to_draft_order_addlines_before = order.lines.count()settings.LANGUAGE_CODE = "fr"- add_variant_to_draft_order(- order, variant, 1, info.context.user, info.context.plugins- )- manager = get_plugins_manager()- add_variant_to_order(order, variant, 1, manager)++ add_variant_to_order(order, variant, 1, info.context.user, info.context.plugins)line = order.lines.last()assert order.lines.count() == lines_before + 1@@@ -145,33 -143,29 +142,31 @@@assert line.product_name == variant.product.name- def test_add_variant_to_draft_order_not_allocates_stock_for_new_variant(+ def test_add_variant_to_order_not_allocates_stock_for_new_variant(- order_with_lines, product+ order_with_lines, product, info):variant = product.variants.get()stock = Stock.objects.get(product_variant=variant)stock_before = get_quantity_allocated_for_stock(stock)- manager = get_plugins_manager()- add_variant_to_draft_order(- add_variant_to_order(order_with_lines, variant, 1, manager)++ add_variant_to_order(+ order_with_lines, variant, 1, info.context.user, info.context.plugins+ )stock.refresh_from_db()assert get_quantity_allocated_for_stock(stock) == stock_before- def test_add_variant_to_draft_order_edits_line_for_existing_variant(- order_with_lines, info- ):-def test_add_variant_to_order_edits_line_for_existing_variant(order_with_lines):++def test_add_variant_to_order_edits_line_for_existing_variant(order_with_lines, info):existing_line = order_with_lines.lines.first()variant = existing_line.variantlines_before = order_with_lines.lines.count()line_quantity_before = existing_line.quantity- manager = get_plugins_manager()- add_variant_to_draft_order(- add_variant_to_order(order_with_lines, variant, 1, manager)++ add_variant_to_order(+ order_with_lines, variant, 1, info.context.user, info.context.plugins+ )existing_line.refresh_from_db()assert order_with_lines.lines.count() == lines_before@@@ -179,8 -173,8 +174,8 @@@assert existing_line.quantity == line_quantity_before + 1- def test_add_variant_to_draft_order_not_allocates_stock_for_existing_variant(+ def test_add_variant_to_order_not_allocates_stock_for_existing_variant(- order_with_lines,+ order_with_lines, info):existing_line = order_with_lines.lines.first()variant = existing_line.variant@@@ -188,10 -182,9 +183,10 @@@stock_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_draft_order(- add_variant_to_order(order_with_lines, variant, 1, manager)++ add_variant_to_order(+ order_with_lines, variant, 1, info.context.user, info.context.plugins+ )stock.refresh_from_db()existing_line.refresh_from_db()@@@ -611,53 -604,47 +606,51 @@@ def test_calculate_order_weight(order_wassert calculated_weight == order_weight-def test_order_weight_add_more_variant(order_with_lines):+def test_order_weight_add_more_variant(order_with_lines, info):variant = order_with_lines.lines.first().variant- add_variant_to_draft_order(- manager = get_plugins_manager()- add_variant_to_order(order_with_lines, variant, 2, manager)++ add_variant_to_order(+ order_with_lines, variant, 2, info.context.user, info.context.plugins+ )order_with_lines.refresh_from_db()++assert order_with_lines.weight == _calculate_order_weight_from_lines(order_with_lines)-def test_order_weight_add_new_variant(order_with_lines, product):+def test_order_weight_add_new_variant(order_with_lines, product, info):variant = product.variants.first()- add_variant_to_draft_order(- manager = get_plugins_manager()- add_variant_to_order(order_with_lines, variant, 2, manager)++++ add_variant_to_order(+ order_with_lines, variant, 2, info.context.user, info.context.plugins+ )order_with_lines.refresh_from_db()++assert order_with_lines.weight == _calculate_order_weight_from_lines(order_with_lines)- def test_order_weight_change_line_quantity(order_with_lines):- line = order_with_lines.lines.first()- new_quantity = line.quantity + 2- change_order_line_quantity(None, line, new_quantity, line.quantity)- order_with_lines.refresh_from_db()- assert order_with_lines.weight == _calculate_order_weight_from_lines(- order_with_lines- )+ def test_order_weight_change_line_quantity(staff_user, lines_info):+ line_info = lines_info[0]+ new_quantity = line_info.quantity + 2+ change_order_line_quantity(staff_user, line_info, new_quantity, line_info.quantity)+ order = line_info.line.order+ assert order.weight == _calculate_order_weight_from_lines(order)- def test_order_weight_delete_line(order_with_lines):- line = order_with_lines.lines.first()- delete_order_line(line)- assert order_with_lines.weight == _calculate_order_weight_from_lines(- order_with_lines- )+ def test_order_weight_delete_line(lines_info):+ order = lines_info[0].line.order+ line_info = lines_info[0]+ delete_order_line(line_info)+ assert order.weight == _calculate_order_weight_from_lines(order)-def test_get_order_weight_non_existing_product(order_with_lines, product):+def test_get_order_weight_non_existing_product(order_with_lines, product, info):# Removing product should not affect order's weightorder = order_with_linesvariant = product.variants.first()- add_variant_to_draft_order(- order, variant, 1, info.context.user, info.context.plugins- )- manager = get_plugins_manager()- add_variant_to_order(order, variant, 1, manager)++ add_variant_to_order(order, variant, 1, info.context.user, info.context.plugins)old_weight = order.get_total_weight()product.delete()diff --cc saleor/order/utils.pyindex 90cbc78623,02e1f1aeff..e530c17034--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@@ -290,7 -296,9 +296,9 @@@ def update_order_status(order)@transaction.atomic- def add_variant_to_draft_order(order, variant, quantity, user, manager, discounts=None):+ def add_variant_to_order(- order, variant, quantity, manager, discounts=None, allocate_stock=False++ order, variant, quantity, user, manager, discounts=None, allocate_stock=False+ ):"""Add total_quantity of variant to order.Returns an order line the variant was added to.