Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add events for adding/removing lines/quantities from drafts
NyanKiyoshi3615b55aa903
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex c6e4a434d4..78feae0535 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -12,12 +12,12 @@ from ...core.exceptions import InsufficientStockfrom ...core.utils.taxes import ZERO_TAXED_MONEYfrom ...discount.models import Voucherfrom ...discount.utils import decrease_voucher_usage, increase_voucher_usage+from ...events.models import OrderEventfrom ...order import OrderStatusfrom ...order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,- change_order_line_quantity, delete_order_line, fulfill_order_line,- recalculate_order)+ change_order_line_quantity, fulfill_order_line, recalculate_order)from ...payment import ChargeStatus, CustomPaymentChoices, PaymentErrorfrom ...payment.utils import (clean_mark_order_as_paid, gateway_capture, gateway_refund, gateway_void,@@ -366,11 +366,11 @@ class CancelOrderLineForm(forms.Form):self.line = kwargs.pop('line')super().__init__(*args, **kwargs)- def cancel_line(self):+ def cancel_line(self, user):if self.line.variant and self.line.variant.track_inventory:deallocate_stock(self.line.variant, self.line.quantity)order = self.line.order- delete_order_line(self.line)+ change_order_line_quantity(user, self.line, self.line.quantity, 0)recalculate_order(order)@@ -403,14 +403,15 @@ class ChangeQuantityForm(forms.ModelForm):self.initial_quantity + variant.quantity_available)}) # noqareturn quantity- def save(self):+ def save(self, user):quantity = self.cleaned_data['quantity']variant = self.instance.variantif variant and variant.track_inventory:# update stock allocationdelta = quantity - self.initial_quantityallocate_stock(variant, delta)- change_order_line_quantity(self.instance, quantity)+ change_order_line_quantity(+ user, self.instance, self.initial_quantity, quantity)recalculate_order(self.instance.order)return self.instance@@ -570,15 +571,18 @@ class AddVariantToOrderForm(forms.Form):self.add_error('quantity', error)return cleaned_data- def save(self):+ def save(self, user):"""Add variant to order.Updates stocks and order."""variant = self.cleaned_data.get('variant')quantity = self.cleaned_data.get('quantity')- add_variant_to_order(+ line = add_variant_to_order(self.order, variant, quantity, self.discounts, self.taxes)+ OrderEvent.draft_added_products(+ order=self.order, source=user,+ order_lines=[(line.quantity, line)]).save()recalculate_order(self.order)diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex f8ce5b7d88..44193477d7 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -256,7 +256,7 @@ def orderline_change_quantity(request, order_pk, line_pk):'variant': line.variant, 'old_quantity': old_quantity,'new_quantity': line.quantity}with transaction.atomic():- form.save()+ form.save(request.user)messages.success(request, msg)return redirect('dashboard:order-details', order_pk=order.pk)elif form.errors:@@ -278,7 +278,7 @@ def orderline_cancel(request, order_pk, line_pk):'Dashboard message related to an order line','Canceled item %s') % linewith transaction.atomic():- form.cancel_line()+ form.cancel_line(request.user)messages.success(request, msg)return redirect('dashboard:order-details', order_pk=order.pk)elif form.errors:@@ -305,7 +305,7 @@ def add_variant_to_order(request, order_pk):'variant': form.cleaned_data.get('variant')}try:with transaction.atomic():- form.save()+ form.save(request.user)msg = pgettext_lazy('Dashboard message related to an order','Added %(quantity)d x %(variant)s') % msg_dictdiff --git a/saleor/events/models/OrderEvent.py b/saleor/events/models/OrderEvent.pyindex 229bac3819..8105b89770 100644--- a/saleor/events/models/OrderEvent.py+++ b/saleor/events/models/OrderEvent.py@@ -1,4 +1,4 @@-from typing import Dict, List, Optional, Union+from typing import Dict, List, Optional, Union, Tuplefrom django.conf import settingsfrom django.contrib.auth.base_user import AbstractBaseUser@@ -44,6 +44,13 @@ class OrderEvent(models.Model):def __repr__(self):return 'OrderEvent(type=%r, user=%r)' % (self.type, self.user)+ @staticmethod+ def _lines_per_quantity_to_str_line_list(quantities_per_order_line):+ return [{+ 'quantity': quantity,+ 'item': str(line)+ } for quantity, line in quantities_per_order_line]+def get_event_display(self):return display_order_event(self)@@ -85,15 +92,28 @@ class OrderEvent(models.Model):def draft_added_products(cls, *,order: Order, source: User,- products: List[ProductVariant]) -> models.Model:- raise NotImplementedError+ order_lines: List[Tuple[int, ProductVariant]]) -> models.Model:++ return cls(+ order=order, type=OrderEvents.DRAFT_ADDED_PRODUCTS.value,+ user=source,+ parameters={+ 'lines': cls._lines_per_quantity_to_str_line_list(order_lines)+ })@classmethoddef draft_removed_products(cls, *,order: Order, source: User,- products: List[ProductVariant]) -> models.Model:- raise NotImplementedError+ order_lines: List[Tuple[int, ProductVariant]]+ ) -> models.Model:++ return cls(+ order=order, type=OrderEvents.DRAFT_REMOVED_PRODUCTS.value,+ user=source,+ parameters={+ 'lines': cls._lines_per_quantity_to_str_line_list(+ order_lines)})@classmethoddef placed_event(@@ -211,10 +231,8 @@ class OrderEvent(models.Model):order=order, type=OrderEvents.FULFILLMENT_FULFILLED_ITEMS.value,user=source,parameters={- 'fulfilled_items': [{- 'quantity': quantity,- 'item': str(line)- } for quantity, line in zip(quantities, order_lines)]})+ 'fulfilled_items': cls._lines_per_quantity_to_str_line_list(+ zip(quantities, order_lines))})@classmethoddef fulfillment_tracking_updated_event(diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 2243c311e2..2abe45d179 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -101,8 +101,8 @@ class DraftOrderCreate(ModelMutation, I18nMixin):cleaned_input['billing_address'] = billing_addressreturn cleaned_input- @classmethod- def save(cls, info, instance, cleaned_input):+ @staticmethod+ def _save_addresses(info, instance, cleaned_input):# Create the draft creation eventshipping_address = cleaned_input.get('shipping_address')if shipping_address:@@ -113,22 +113,48 @@ class DraftOrderCreate(ModelMutation, I18nMixin):billing_address.save()instance.billing_address = billing_address.get_copy()+ @staticmethod+ def _save_lines(info, instance, events, quantities, variants):+ if variants and quantities:+ lines = []+ for variant, quantity in zip(variants, quantities):+ lines.append((quantity, variant))+ add_variant_to_order(+ instance, variant, quantity, allow_overselling=True,+ track_inventory=False)++ # Add event+ events.append(OrderEvent.draft_added_products(+ order=instance, source=info.context.user, order_lines=lines))++ @staticmethod+ def _commit_changes(info, instance, cleaned_input, events):# Create draft created event if the instance is from scratchif not instance.pk:- OrderEvent.draft_created_event(- order=instance, source=info.context.user).save()+ events.append(OrderEvent.draft_created_event(+ order=instance, source=info.context.user))super().save(info, instance, cleaned_input)instance.save(update_fields=['billing_address', 'shipping_address'])- variants = cleaned_input.get('variants')- quantities = cleaned_input.get('quantities')- if variants and quantities:- for variant, quantity in zip(variants, quantities):- add_variant_to_order(- instance, variant, quantity, allow_overselling=True,- track_inventory=False)+ @classmethod+ def save(cls, info, instance, cleaned_input):+ events = []++ # Process addresses+ cls._save_addresses(info, instance, cleaned_input)++ # Save any changes create/update the draft+ cls._commit_changes(info, instance, cleaned_input, events)++ # Process any lines to add+ cls._save_lines(+ info, instance, events,+ cleaned_input.get('quantities'), cleaned_input.get('variants'))++ # Post-process the resultsrecalculate_order(instance)+ OrderEvent.objects.bulk_create(events)class DraftOrderUpdate(DraftOrderCreate):@@ -240,7 +266,7 @@ class DraftOrderLinesCreate(BaseMutation):if order.status != OrderStatus.DRAFT:raise ValidationError({'id': 'Only draft orders can be edited.'})- lines = []+ lines_to_add = []for input_line in data.get('input'):variant_id = input_line['variant_id']variant = cls.get_node_or_error(@@ -248,14 +274,22 @@ class DraftOrderLinesCreate(BaseMutation):quantity = input_line['quantity']if quantity > 0:if variant:- line = add_variant_to_order(- order, variant, quantity, allow_overselling=True)- lines.append(line)+ lines_to_add.append((quantity, variant))else:raise ValidationError({'quantity':'Ensure this value is greater than or equal to 1.'})+ # Add the lines+ lines = [+ add_variant_to_order(+ order, variant, quantity, allow_overselling=True)+ for quantity, variant in lines_to_add]++ # Create the event+ OrderEvent.draft_added_products(+ order=order, source=info.context.user, order_lines=lines_to_add)+recalculate_order(order)return DraftOrderLinesCreate(order=order, order_lines=lines)@@ -283,6 +317,12 @@ class DraftOrderLineDelete(BaseMutation):db_id = line.iddelete_order_line(line)line.id = db_id++ # Create the removal event+ OrderEvent.draft_removed_products(+ order=order, source=info.context.user,+ order_lines=[(line.quantity, line)]).save()+recalculate_order(order)return DraftOrderLineDelete(order=order, order_line=line)@@ -304,6 +344,7 @@ class DraftOrderLineUpdate(ModelMutation):@classmethoddef clean_input(cls, info, instance, data):+ instance.old_quantity = instance.quantitycleaned_input = super().clean_input(info, instance, data)if instance.order.status != OrderStatus.DRAFT:raise ValidationError({'id': 'Only draft orders can be edited.'})@@ -317,7 +358,9 @@ class DraftOrderLineUpdate(ModelMutation):@classmethoddef save(cls, info, instance, cleaned_input):- change_order_line_quantity(instance, instance.quantity)+ change_order_line_quantity(+ info.context.user, instance,+ instance.old_quantity, instance.quantity)recalculate_order(instance.order)@classmethoddiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 9fba5262b5..079f75fbfe 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -288,7 +288,7 @@ def add_variant_to_order(return line-def change_order_line_quantity(line, new_quantity):+def change_order_line_quantity(user, line, old_quantity, new_quantity):"""Change the quantity of ordered items in a order line."""if new_quantity:line.quantity = new_quantity@@ -296,6 +296,18 @@ def change_order_line_quantity(line, new_quantity):else:delete_order_line(line)+ quantity_diff = old_quantity - new_quantity++ # Create the removal event+ if quantity_diff > 0:+ OrderEvent.draft_removed_products(+ order=line.order, source=user,+ order_lines=[(quantity_diff, line)]).save()+ elif quantity_diff < 0:+ OrderEvent.draft_added_products(+ order=line.order, source=user,+ order_lines=[(quantity_diff * -1, line)]).save()+def delete_order_line(line):"""Delete an order line from an order."""diff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex 5025a1f87b..6ef9167fcb 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -785,14 +785,21 @@ DRAFT_ORDER_LINE_UPDATE_MUTATION = """def test_draft_order_line_update(- draft_order, permission_manage_orders, staff_api_client):+ draft_order, permission_manage_orders, staff_api_client, staff_user):query = DRAFT_ORDER_LINE_UPDATE_MUTATIONorder = draft_orderline = order.lines.first()new_quantity = 1+ removed_quantity = 2line_id = graphene.Node.to_global_id('OrderLine', line.id)variables = {'lineId': line_id, 'quantity': new_quantity}+ # Ensure the line has the expected quantity+ assert line.quantity == 3++ # No event should exist yet+ assert not OrderEvent.objects.exists()+# mutation should fail without proper permissionsresponse = staff_api_client.post_graphql(query, variables)assert_no_permission(response)@@ -804,6 +811,12 @@ def test_draft_order_line_update(data = content['data']['draftOrderLineUpdate']assert data['orderLine']['quantity'] == new_quantity+ removed_items_event = OrderEvent.objects.last() # type: OrderEvent+ assert removed_items_event.type == OrderEvents.DRAFT_REMOVED_PRODUCTS.value+ assert removed_items_event.user == staff_user+ assert removed_items_event.parameters == {+ 'lines': [{'quantity': removed_quantity, 'item': str(line)}]}+# mutation should fail when quantity is lower than 1variables = {'lineId': line_id, 'quantity': 0}response = staff_api_client.post_graphql(query, variables)diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex 2ff22353d2..6c9cec9080 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -261,7 +261,8 @@ def test_view_void_order_invalid_payment_refunded_status(@pytest.mark.integration@pytest.mark.parametrize('track_inventory', (True, False))-def test_view_cancel_order_line(admin_client, draft_order, track_inventory):+def test_view_cancel_order_line(+ admin_client, draft_order, track_inventory, admin_user):lines_before = draft_order.lines.all()lines_before_count = lines_before.count()line = lines_before.first()@@ -271,6 +272,8 @@ def test_view_cancel_order_line(admin_client, draft_order, track_inventory):line.variant.track_inventory = track_inventoryline.variant.save()+ assert not OrderEvent.objects.exists()+url = reverse('dashboard:orderline-cancel', kwargs={'order_pk': draft_order.pk,@@ -295,6 +298,12 @@ def test_view_cancel_order_line(admin_client, draft_order, track_inventory):else:assert line.variant.quantity_allocated == quantity_allocated_before+ removed_items_event = OrderEvent.objects.last()+ assert removed_items_event.type == OrderEvents.DRAFT_REMOVED_PRODUCTS.value+ assert removed_items_event.user == admin_user+ assert removed_items_event.parameters == {+ 'lines': [{'quantity': line.quantity, 'item': str(line)}]}+url = reverse('dashboard:orderline-cancel', kwargs={'order_pk': draft_order.pk,@@ -309,7 +318,7 @@ def test_view_cancel_order_line(admin_client, draft_order, track_inventory):@pytest.mark.integration@pytest.mark.parametrize('track_inventory', (True, False))def test_view_change_order_line_quantity(- admin_client, draft_order, track_inventory):+ admin_client, draft_order, track_inventory, admin_user):lines_before_quantity_change = draft_order.lines.all()lines_before_quantity_change_count = lines_before_quantity_change.count()line = lines_before_quantity_change.first()@@ -317,6 +326,8 @@ def test_view_change_order_line_quantity(line.variant.track_inventory = track_inventoryline.variant.save()+ assert not OrderEvent.objects.exists()+url = reverse('dashboard:orderline-change-quantity',kwargs={'order_pk': draft_order.pk, 'line_pk': line.pk})@@ -341,6 +352,12 @@ def test_view_change_order_line_quantity(else:assert line.variant.quantity_allocated == 3+ removed_items_event = OrderEvent.objects.last()+ assert removed_items_event.type == OrderEvents.DRAFT_REMOVED_PRODUCTS.value+ assert removed_items_event.user == admin_user+ assert removed_items_event.parameters == {+ 'lines': [{'quantity': 1, 'item': str(line)}]}+line.refresh_from_db()# source line quantity should be decreased to 2assert line.quantity == 2@@ -465,13 +482,15 @@ def test_view_fulfillment_packing_slips_without_shipping(assert response['content-type'] == 'application/pdf'-def test_view_add_variant_to_order(admin_client, order_with_lines):+def test_view_add_variant_to_order(admin_client, order_with_lines, admin_user):order_with_lines.status = OrderStatus.DRAFTorder_with_lines.save()variant = ProductVariant.objects.get(sku='SKU_A')line = OrderLine.objects.get(product_sku='SKU_A')line_quantity_before = line.quantity+ assert not OrderEvent.objects.exists()+added_quantity = 2url = reverse('dashboard:add-variant-to-order',@@ -486,6 +505,12 @@ def test_view_add_variant_to_order(admin_client, order_with_lines):'dashboard:order-details', kwargs={'order_pk': order_with_lines.pk})assert line.quantity == line_quantity_before + added_quantity+ removed_items_event = OrderEvent.objects.last()+ assert removed_items_event.type == OrderEvents.DRAFT_ADDED_PRODUCTS.value+ assert removed_items_event.user == admin_user+ assert removed_items_event.parameters == {+ 'lines': [{'quantity': line.quantity, 'item': str(line)}]}+def test_view_change_fulfillment_tracking(admin_client, fulfilled_order):fulfillment = fulfilled_order.fulfillments.first()diff --git a/tests/test_order_utils.py b/tests/test_order_utils.pynew file mode 100644index 0000000000..4a88d46499--- /dev/null+++ b/tests/test_order_utils.py@@ -0,0 +1,41 @@+import pytest++from saleor.events.models import OrderEvent+from saleor.events.types import OrderEvents+from saleor.order.utils import change_order_line_quantity+++ 'previous_quantity,new_quantity,added_count,removed_count', (+ (5, 2, 0, 3),+ (2, 5, 3, 0),+ (2, 0, 0, 2),+ (5, 5, 0, 0)))+def test_change_quantity_generates_proper_event(+ previous_quantity, new_quantity, added_count, removed_count,+ order_with_lines, staff_user):++ assert not OrderEvent.objects.exists()++ line = order_with_lines.lines.last()+ line.quantity = previous_quantity++ change_order_line_quantity(+ staff_user, line, previous_quantity, new_quantity)++ if removed_count:+ expected_type = OrderEvents.DRAFT_REMOVED_PRODUCTS.value+ expected_quantity = removed_count+ elif added_count:+ expected_type = OrderEvents.DRAFT_ADDED_PRODUCTS.value+ expected_quantity = added_count+ else:+ # No event should have occurred+ assert not OrderEvent.objects.exists()+ return++ new_event = OrderEvent.objects.last() # type: OrderEvent+ assert new_event.type == expected_type+ assert new_event.user == staff_user+ assert new_event.parameters == {+ 'lines': [{'quantity': expected_quantity, 'item': str(line)}]}