Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Remove DeliveryGroup

Anna Siwik5090572c5315
diff --git a/requirements.in b/requirements.in
index 27bba77ccf..e2fa99c1cd 100644
--- a/requirements.in
+++ b/requirements.in
@@ -10,7 +10,6 @@ django-bootstrap4>=0.0.4
django-cache-url>=1.0.0
django-countries>=5.2
django-filter==1.1
-django-fsm>=2.6.0
django-impersonate==1.3
django-mptt>=0.7.1
django-payments>=0.12.1
diff --git a/requirements.txt b/requirements.txt
index 20dd015e42..1df942e6b0 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -31,7 +31,6 @@ django-celery-results==1.0.1
django-countries==5.2
django-elasticsearch-dsl==0.4.4
django-filter==1.1
-django-fsm==2.6.0
django-impersonate==1.3
django-js-asset==1.0.0 # via django-mptt
django-mptt==0.9.0
diff --git a/saleor/core/analytics.py b/saleor/core/analytics.py
index be88dc3381..a7169500b2 100644
--- a/saleor/core/analytics.py
+++ b/saleor/core/analytics.py
@@ -47,13 +47,12 @@ def report_view(client_id, path, language, headers):
def report_order(client_id, order):
- for group in order:
- items = [
- ga.Item(
- ol.product_name, ol.get_price_per_item(), quantity=ol.quantity,
- item_id=ol.product_sku)
- for ol in group]
- trans = ga.Transaction(
- '%s-%s' % (order.id, group.id), items, revenue=group.get_total(),
- shipping=group.order.shipping_price)
- _report(client_id, trans, {})
+ items = [
+ ga.Item(
+ ol.product_name, ol.get_price_per_item(), quantity=ol.quantity,
+ item_id=ol.product_sku)
+ for ol in order]
+ trans = ga.Transaction(
+ '%s' % (order.id,), items, revenue=order.get_total(),
+ shipping=order.shipping_price)
+ _report(client_id, trans, {})
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 48cbde7767..ba7dae8eed 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -17,8 +17,7 @@ from ...account.models import Address, User
from ...account.utils import store_user_address
from ...discount import DiscountValueType, VoucherType
from ...discount.models import Sale, Voucher
-from ...order import GroupStatus
-from ...order.models import DeliveryGroup, Order, OrderLine, Payment
+from ...order.models import Order, OrderLine, Payment
from ...product.models import (
AttributeChoiceValue, Category, Collection, Product, ProductAttribute,
ProductImage, ProductType, ProductVariant, Stock, StockLocation)
@@ -357,8 +356,7 @@ def create_fake_user():
return user
-def create_payment(delivery_group):
- order = delivery_group.order
+def create_payment(order):
status = random.choice(
[
PaymentStatus.WAITING,
@@ -385,21 +383,7 @@ def create_payment(delivery_group):
return payment
-def create_delivery_group(order):
- region = order.shipping_address.country
- if region not in DELIVERY_REGIONS:
- region = ANY_COUNTRY
- shipping_method = fake.shipping_method()
- shipping_country = shipping_method.price_per_country.get_or_create(
- country_code=region, defaults={'price': fake.money()})[0]
- delivery_group = DeliveryGroup.objects.create(
- status=random.choice([GroupStatus.NEW, GroupStatus.SHIPPED]),
- order=order,
- shipping_method_name=str(shipping_country))
- return delivery_group
-
-
-def create_order_line(delivery_group):
+def create_order_line(order):
product = Product.objects.all().order_by('?')[0]
variant = product.variants.all()[0]
quantity = random.randrange(1, 5)
@@ -408,7 +392,7 @@ def create_order_line(delivery_group):
stock.quantity_allocated += quantity
stock.save()
return OrderLine.objects.create(
- delivery_group=delivery_group,
+ order=order,
product=product,
product_name=product.name,
product_sku=variant.sku,
@@ -419,9 +403,9 @@ def create_order_line(delivery_group):
unit_price=TaxedMoney(net=product.price, gross=product.price))
-def create_order_lines(delivery_group, how_many=10):
+def create_order_lines(order, how_many=10):
for dummy in range(how_many):
- yield create_order_line(delivery_group)
+ yield create_order_line(order)
def create_fake_order():
@@ -441,14 +425,13 @@ def create_fake_order():
address.first_name, address.last_name)}
order = Order.objects.create(**user_data)
- delivery_group = create_delivery_group(order)
- lines = create_order_lines(delivery_group, random.randrange(1, 5))
+ lines = create_order_lines(order, random.randrange(1, 5))
order.total = sum(
[line.get_total() for line in lines], order.shipping_price)
order.save()
- create_payment(delivery_group)
+ create_payment(order)
return order
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 61e0f1d55d..98e4045474 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -1,6 +1,6 @@
from django import forms
from django.conf import settings
-from django.core.validators import MaxValueValidator, MinValueValidator
+from django.core.validators import MinValueValidator
from django.urls import reverse_lazy
from django.utils.translation import npgettext_lazy, pgettext_lazy
from django_prices.forms import MoneyField
@@ -11,13 +11,11 @@ from ...account.i18n import (
from ...cart.forms import QuantityField
from ...core.exceptions import InsufficientStock
from ...discount.utils import decrease_voucher_usage
-from ...order import GroupStatus
from ...order.emails import send_note_confirmation
-from ...order.models import DeliveryGroup, OrderLine, OrderNote
+from ...order.models import OrderLine, OrderNote
from ...order.utils import (
add_variant_to_order, cancel_order, change_order_line_quantity,
- merge_duplicates_into_order_line, move_order_line_to_group,
- recalculate_order, remove_empty_groups)
+ merge_duplicates_into_order_line, recalculate_order)
from ...product.models import Product, ProductVariant, Stock
from ...product.utils import allocate_stock, deallocate_stock
from ..forms import AjaxSelect2ChoiceField
@@ -102,42 +100,6 @@ class ReleasePaymentForm(ManagePaymentForm):
return self.try_payment_action(self.payment.release)
-class MoveLinesForm(forms.Form):
- """Allows splitting an order line into an existing or new group."""
-
- quantity = QuantityField(
- label=pgettext_lazy('Move lines form label', 'Quantity'),
- validators=[MinValueValidator(1)])
- target_group = forms.ModelChoiceField(
- queryset=DeliveryGroup.objects.none(), required=False,
- empty_label=pgettext_lazy(
- 'Shipment group value for `target_group` field', 'New shipment'),
- label=pgettext_lazy('Move lines form label', 'Target shipment'))
-
- def __init__(self, *args, **kwargs):
- self.line = kwargs.pop('line')
- super().__init__(*args, **kwargs)
- self.fields['quantity'].validators.append(
- MaxValueValidator(self.line.quantity))
- self.fields['quantity'].widget.attrs.update({
- 'max': self.line.quantity, 'min': 1})
- self.old_group = self.line.delivery_group
- queryset = self.old_group.order.groups.exclude(
- pk=self.old_group.pk).exclude(status=GroupStatus.CANCELLED)
- self.fields['target_group'].queryset = queryset
-
- def move_lines(self):
- how_many = self.cleaned_data.get('quantity')
- target_group = self.cleaned_data.get('target_group')
- if not target_group:
- # For new group we use the same shipping name but zero price
- target_group = self.old_group.order.groups.create(
- status=self.old_group.status,
- shipping_method_name=self.old_group.shipping_method_name)
- move_order_line_to_group(self.line, target_group, how_many)
- return target_group
-
-
class CancelOrderLineForm(forms.Form):
def __init__(self, *args, **kwargs):
@@ -147,9 +109,13 @@ class CancelOrderLineForm(forms.Form):
def cancel_line(self):
if self.line.stock:
deallocate_stock(self.line.stock, self.line.quantity)
- order = self.line.delivery_group.order
- self.line.quantity = 0
- remove_empty_groups(self.line)
+ order = self.line.order
+ self.line.delete()
+ if not order.lines.exists():
+ order.create_history_entry(
+ content=pgettext_lazy(
+ 'Order status history entry',
+ 'Order cancelled. No items in order'))
recalculate_order(order)
@@ -192,65 +158,14 @@ class ChangeQuantityForm(forms.ModelForm):
delta = quantity - self.initial_quantity
allocate_stock(stock, delta)
change_order_line_quantity(self.instance, quantity)
- recalculate_order(self.instance.delivery_group.order)
+ recalculate_order(self.instance.order)
return self.instance
-class ShipGroupForm(forms.ModelForm):
- """Dispatch a group and optionally assign a tracking number.
-
- This process involves permanently decreasing the previously allocated
- stock.
- """
-
- class Meta:
- model = DeliveryGroup
- fields = ['tracking_number']
- labels = {
- 'tracking_number': pgettext_lazy(
- 'Shipment tracking number', 'Tracking number')}
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.fields['tracking_number'].widget.attrs.update(
- {'placeholder': pgettext_lazy(
- 'Ship group form field placeholder',
- 'Parcel tracking number')})
-
- def clean(self):
- if self.instance.status != GroupStatus.NEW:
- raise forms.ValidationError(
- pgettext_lazy(
- 'Ship group form error',
- 'Cannot ship this group'),
- code='invalid')
-
- def save(self, commit=True):
- self.instance.ship(self.cleaned_data.get('tracking_number'))
- return super().save(commit)
-
-
-class CancelGroupForm(forms.ModelForm):
- """Allow canceling a single group in an order.
-
- Deallocates or increases corresponding stocks, depending whether new
- or shipped group is cancelled.
- """
-
- class Meta:
- model = DeliveryGroup
- fields = []
-
- def save(self, commit=True):
- self.instance.cancel()
- return super().save(commit)
-
-
class CancelOrderForm(forms.Form):
"""Allow canceling an entire order.
- Deallocates or increases corresponding stocks in each delivery group,
- depending whether new or shipped group is cancelled.
+ Deallocates corresponding stocks for each order line.
"""
def __init__(self, *args, **kwargs):
@@ -347,7 +262,7 @@ class ChangeStockForm(forms.ModelForm):
class AddVariantToOrderForm(forms.Form):
- """Allow adding lines with given quantity to a shipment group."""
+ """Allow adding lines with given quantity to an order."""
variant = AjaxSelect2ChoiceField(
queryset=ProductVariant.objects.filter(
@@ -355,7 +270,7 @@ class AddVariantToOrderForm(forms.Form):
fetch_data_url=reverse_lazy('dashboard:ajax-available-variants'))
quantity = QuantityField(
label=pgettext_lazy(
- 'Add variant to shipment group form label', 'Quantity'),
+ 'Add variant to order form label', 'Quantity'),
validators=[MinValueValidator(1)])
def __init__(self, *args, **kwargs):
diff --git a/saleor/dashboard/order/urls.py b/saleor/dashboard/order/urls.py
index 63b94d560c..c36d25624c 100644
--- a/saleor/dashboard/order/urls.py
+++ b/saleor/dashboard/order/urls.py
@@ -22,21 +22,15 @@ urlpatterns = [
url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/change/$',
views.orderline_change_quantity, name='orderline-change-quantity'),
- url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/split/$',
- views.orderline_split, name='orderline-split'),
url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/cancel/$',
views.orderline_cancel, name='orderline-cancel'),
url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/change-stock/$',
views.orderline_change_stock, name='orderline-change-stock'),
url(r'^(?P<order_pk>\d+)/remove-voucher/$',
views.remove_order_voucher, name='order-remove-voucher'),
- url(r'^(?P<order_pk>\d+)/shipment/(?P<group_pk>\d+)/ship/$',
- views.ship_delivery_group, name='ship-delivery-group'),
- url(r'^(?P<order_pk>\d+)/shipment/(?P<group_pk>\d+)/cancel/$',
- views.cancel_delivery_group, name='cancel-delivery-group'),
url(r'^(?P<order_pk>\d+)/add-variant/$',
views.add_variant_to_order, name='add-variant-to-order'),
url(r'^(?P<order_pk>\d+)/invoice/$',
views.order_invoice, name='order-invoice'),
- url(r'^(?P<group_pk>\d+)/packing-slips/$',
+ url(r'^(?P<order_pk>\d+)/packing-slips/$',
views.order_packing_slip, name='order-packing-slips')]
diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.py
index 6897694a8a..98b7c95d74 100644
--- a/saleor/dashboard/order/utils.py
+++ b/saleor/dashboard/order/utils.py
@@ -24,16 +24,14 @@ def _create_pdf(rendered_template, absolute_url):
def create_invoice_pdf(order, absolute_url):
- shipping_methods = [
- {'name': d.shipping_method_name} for d in order.groups.all()]
- ctx = {'order': order, 'shipping_methods': shipping_methods}
+ ctx = {'order': order}
rendered_template = get_template(INVOICE_TEMPLATE).render(ctx)
pdf_file = _create_pdf(rendered_template, absolute_url)
return pdf_file, order
-def create_packing_slip_pdf(group, absolute_url):
- ctx = {'group': group}
+def create_packing_slip_pdf(order, absolute_url):
+ ctx = {'order': order}
rendered_template = get_template(PACKING_SLIP_TEMPLATE).render(ctx)
pdf_file = _create_pdf(rendered_template, absolute_url)
- return pdf_file, group
+ return pdf_file, order
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index a75c6b0d17..9e6f3bc4e6 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -13,16 +13,15 @@ from prices import Money, TaxedMoney
from ...core.exceptions import InsufficientStock
from ...core.utils import ZERO_TAXED_MONEY, get_paginator_items
-from ...order import GroupStatus
-from ...order.models import DeliveryGroup, Order, OrderLine, OrderNote
+from ...order import OrderStatus
+from ...order.models import Order, OrderLine, OrderNote
from ...product.models import StockLocation
from ..views import staff_member_required
from .filters import OrderFilter
from .forms import (
- AddressForm, AddVariantToOrderForm, CancelGroupForm,
- CancelOrderForm, CancelOrderLineForm, CapturePaymentForm,
- ChangeQuantityForm, ChangeStockForm, MoveLinesForm, OrderNoteForm,
- RefundPaymentForm, ReleasePaymentForm, RemoveVoucherForm, ShipGroupForm)
+ AddressForm, AddVariantToOrderForm, CancelOrderForm, CancelOrderLineForm,
+ CapturePaymentForm, ChangeQuantityForm, ChangeStockForm, OrderNoteForm,
+ RefundPaymentForm, ReleasePaymentForm, RemoveVoucherForm)
from .utils import (
create_invoice_pdf, create_packing_slip_pdf, get_statics_absolute_url)
@@ -52,15 +51,12 @@ def order_details(request, order_pk):
notes = order.notes.all()
all_payments = order.payments.exclude(status=PaymentStatus.INPUT)
payment = order.payments.last()
- groups = list(order)
captured = preauthorized = ZERO_TAXED_MONEY
balance = captured - order.total
if payment:
can_capture = (
payment.status == PaymentStatus.PREAUTH and
- any([
- group.status != GroupStatus.CANCELLED
- for group in order.groups.all()]))
+ order.status != OrderStatus.CANCELLED)
can_release = payment.status == PaymentStatus.PREAUTH
can_refund = payment.status == PaymentStatus.CONFIRMED
preauthorized = payment.get_total_price()
@@ -71,11 +67,10 @@ def order_details(request, order_pk):
can_capture = can_release = can_refund = False
is_many_stock_locations = StockLocation.objects.count() > 1
ctx = {'order': order, 'all_payments': all_payments, 'payment': payment,
- 'notes': notes, 'groups': groups, 'captured': captured,
+ 'notes': notes, 'captured': captured, 'balance': balance,
'preauthorized': preauthorized, 'can_capture': can_capture,
'can_release': can_release, 'can_refund': can_refund,
- 'is_many_stock_locations': is_many_stock_locations,
- 'balance': balance}
+ 'is_many_stock_locations': is_many_stock_locations}
return TemplateResponse(request, 'dashboard/order/detail.html', ctx)
@@ -171,8 +166,7 @@ def release_payment(request, order_pk, payment_pk):
@permission_required('order.edit_order')
def orderline_change_quantity(request, order_pk, line_pk):
order = get_object_or_404(Order, pk=order_pk)
- line = get_object_or_404(OrderLine.objects.filter(
- delivery_group__order=order), pk=line_pk)
+ line = get_object_or_404(order.lines.all(), pk=line_pk)
form = ChangeQuantityForm(request.POST or None, instance=line)
status = 200
old_quantity = line.quantity
@@ -195,48 +189,11 @@ def orderline_change_quantity(request, order_pk, line_pk):
return TemplateResponse(request, template, ctx, status=status)
-@staff_member_required
-@permission_required('order.edit_order')
-def orderline_split(request, order_pk, line_pk):
- order = get_object_or_404(Order, pk=order_pk)
- line = get_object_or_404(OrderLine.objects.filter(
- delivery_group__order=order), pk=line_pk)
- form = MoveLinesForm(request.POST or None, line=line)
- line_pk = None
- if line:
- line_pk = line.pk
- status = 200
- if form.is_valid():
- old_group = line.delivery_group
- how_many = form.cleaned_data.get('quantity')
- with transaction.atomic():
- target_group = form.move_lines()
- if not old_group.pk:
- old_group = pgettext_lazy(
- 'Dashboard message related to a shipment group',
- 'removed group')
- msg = pgettext_lazy(
- 'Dashboard message related to shipment groups',
- 'Moved %(how_many)s items %(item)s from %(old_group)s'
- ' to %(new_group)s') % {
- 'how_many': how_many, 'item': line, 'old_group': old_group,
- 'new_group': target_group}
- order.history.create(content=msg, user=request.user)
- messages.success(request, msg)
- return redirect('dashboard:order-details', order_pk=order.pk)
- elif form.errors:
- status = 400
- ctx = {'order': order, 'object': line, 'form': form, 'line_pk': line_pk}
- template = 'dashboard/order/modal/split_order_line.html'
- return TemplateResponse(request, template, ctx, status=status)
-
-
@staff_member_required
@permission_required('order.edit_order')
def orderline_cancel(request, order_pk, line_pk):
order = get_object_or_404(Order, pk=order_pk)
- line = get_object_or_404(OrderLine.objects.filter(
- delivery_group__order=order), pk=line_pk)
+ line = get_object_or_404(order.lines.all(), pk=line_pk)
form = CancelOrderLineForm(data=request.POST or None, line=line)
status = 200
if form.is_valid():
@@ -256,53 +213,6 @@ def orderline_cancel(request, order_pk, line_pk):
ctx, status=status)
-@staff_member_required
-@permission_required('order.edit_order')
-def ship_delivery_group(request, order_pk, group_pk):
- order = get_object_or_404(
- Order.objects.select_related('shipping_address'), pk=order_pk)
- group = get_object_or_404(order.groups.all(), pk=group_pk)
- form = ShipGroupForm(request.POST or None, instance=group)
- status = 200
- if form.is_valid():
- with transaction.atomic():
- form.save()
- msg = pgettext_lazy(
- 'Dashboard message related to a shipment group',
- 'Shipped %s') % group
- messages.success(request, msg)
- order.history.create(content=msg, user=request.user)
- return redirect('dashboard:order-details', order_pk=order_pk)
- elif form.errors:
- status = 400
- ctx = {'order': order, 'group': group, 'form': form}
- template = 'dashboard/order/modal/ship_shipment_group.html'
- return TemplateResponse(request, template, ctx, status=status)
-
-
-@staff_member_required
-@permission_required('order.edit_order')
-def cancel_delivery_group(request, order_pk, group_pk):
- order = get_object_or_404(Order, pk=order_pk)
- group = get_object_or_404(order.groups.all(), pk=group_pk)
- form = CancelGroupForm(request.POST or None, instance=group)
- status = 200
- if form.is_valid():
- with transaction.atomic():
- form.save()
- msg = pgettext_lazy(
- 'Dashboard message related to a shipment group',
- 'Cancelled %s') % group
- messages.success(request, msg)
- order.history.create(content=msg, user=request.user)
- return redirect('dashboard:order-details', order_pk=order_pk)
- elif form.errors:
- status = 400
- ctx = {'order': order, 'group': group}
- template = 'dashboard/order/modal/cancel_shipment_group.html'
- return TemplateResponse(request, template, ctx, status=status)
-
-
@staff_member_required
@permission_required('order.edit_order')
def add_variant_to_order(request, order_pk):
@@ -333,7 +243,7 @@ def add_variant_to_order(request, order_pk):
elif form.errors:
status = 400
ctx = {'order': order, 'form': form}
- template = 'dashboard/order/modal/add_variant_to_group.html'
+ template = 'dashboard/order/modal/add_variant_to_order.html'
return TemplateResponse(request, template, ctx, status=status)
@@ -413,7 +323,7 @@ def remove_order_voucher(request, order_pk):
@permission_required('order.edit_order')
def order_invoice(request, order_pk):
orders = Order.objects.prefetch_related(
- 'user', 'shipping_address', 'billing_address', 'voucher', 'groups')
+ 'user', 'shipping_address', 'billing_address', 'voucher')
order = get_object_or_404(orders, pk=order_pk)
absolute_url = get_statics_absolute_url(request)
pdf_file, order = create_invoice_pdf(order, absolute_url)
@@ -425,15 +335,14 @@ def order_invoice(request, order_pk):
@staff_member_required
@permission_required('order.edit_order')
-def order_packing_slip(request, group_pk):
- groups = DeliveryGroup.objects.prefetch_related(
- 'lines', 'order', 'order__user', 'order__shipping_address',
- 'order__billing_address')
- group = get_object_or_404(groups, pk=group_pk)
+def order_packing_slip(request, order_pk):
+ orders = Order.objects.prefetch_related(
+ 'lines', 'user', 'shipping_address', 'billing_address')
+ order = get_object_or_404(orders, pk=order_pk)
absolute_url = get_statics_absolute_url(request)
- pdf_file, group = create_packing_slip_pdf(group, absolute_url)
+ pdf_file, order = create_packing_slip_pdf(order, absolute_url)
response = HttpResponse(pdf_file, content_type='application/pdf')
- name = "packing-slip-%s-%s" % (group.order.id, group.id)
+ name = "packing-slip-%s" % (order.id,)
response['Content-Disposition'] = 'filename=%s' % name
return response
@@ -453,5 +362,5 @@ def orderline_change_stock(request, order_pk, line_pk):
elif form.errors:
status = 400
ctx = {'order_pk': order_pk, 'line_pk': line_pk, 'form': form}
- template = 'dashboard/order/modal/shipment_group_stock.html'
+ template = 'dashboard/order/modal/order_line_stock.html'
return TemplateResponse(request, template, ctx, status=status)
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 44fc7ed0f8..e4256fee27 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -13,19 +13,10 @@ class OrderAppConfig(AppConfig):
class OrderStatus:
OPEN = 'open'
+ CANCELLED = 'cancelled'
CLOSED = 'closed'
CHOICES = [
(OPEN, pgettext_lazy('order status', 'Open')),
+ (CANCELLED, pgettext_lazy('order status', 'Cancelled')),
(CLOSED, pgettext_lazy('order status', 'Closed'))]
-
-
-class GroupStatus:
- NEW = 'new'
- CANCELLED = 'cancelled'
- SHIPPED = 'shipped'
-
- CHOICES = [
- (NEW, pgettext_lazy('group status', 'Processing')),
- (CANCELLED, pgettext_lazy('group status', 'Cancelled')),
- (SHIPPED, pgettext_lazy('group status', 'Shipped'))]
diff --git a/saleor/order/migrations/0034_auto_20180210_0422.py b/saleor/order/migrations/0034_auto_20180210_0422.py
index d53bce24c8..a79aabb9df 100644
--- a/saleor/order/migrations/0034_auto_20180210_0422.py
+++ b/saleor/order/migrations/0034_auto_20180210_0422.py
@@ -47,5 +47,5 @@ class Migration(migrations.Migration):
name='order_line',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='order.OrderLine'),
),
- migrations.RunPython(assign_order_to_lines)
+ migrations.RunPython(assign_order_to_lines, migrations.RunPython.noop)
]
diff --git a/saleor/order/migrations/0035_auto_20180210_0427.py b/saleor/order/migrations/0035_auto_20180210_1359.py
similarity index 70%
rename from saleor/order/migrations/0035_auto_20180210_0427.py
rename to saleor/order/migrations/0035_auto_20180210_1359.py
index 55e26985f7..715c89e2bc 100644
--- a/saleor/order/migrations/0035_auto_20180210_0427.py
+++ b/saleor/order/migrations/0035_auto_20180210_1359.py
@@ -1,4 +1,4 @@
-# Generated by Django 2.0.2 on 2018-02-10 10:27
+# Generated by Django 2.0.2 on 2018-02-10 19:59
from django.db import migrations, models
import django.db.models.deletion
@@ -11,6 +11,10 @@ class Migration(migrations.Migration):
]
operations = [
+ migrations.RemoveField(
+ model_name='deliverygroup',
+ name='order',
+ ),
migrations.RemoveField(
model_name='orderline',
name='delivery_group',
@@ -20,4 +24,7 @@ class Migration(migrations.Migration):
name='order',
field=models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='order.Order'),
),
+ migrations.DeleteModel(
+ name='DeliveryGroup',
+ ),
]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index c4f948d789..e8da8ab964 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -8,31 +8,28 @@ from django.db.models import F, Sum, Q
from django.urls import reverse
from django.utils.timezone import now
from django.utils.translation import pgettext_lazy
-from django_fsm import FSMField, transition
from django_prices.models import MoneyField, TaxedMoneyField
from payments import PaymentStatus, PurchasedItem
from payments.models import BasePayment
from prices import Money, TaxedMoney
-from . import GroupStatus, OrderStatus
+from . import OrderStatus
from ..account.models import Address
from ..core.utils import ZERO_TAXED_MONEY, build_absolute_uri
from ..discount.models import Voucher
from ..product.models import Product
-from .transitions import (
- cancel_delivery_group, process_delivery_group, ship_delivery_group)
class OrderQuerySet(models.QuerySet):
"""Filter orders by status deduced from fulfillment quantities."""
def open(self):
- """Orders having at least one shipment group with status NEW."""
- return self.filter(Q(groups__status=GroupStatus.NEW))
+ # TODO: specify new order statuses
+ return self
def closed(self):
- """Orders having no shipment groups with status NEW."""
- return self.filter(~Q(groups__status=GroupStatus.NEW))
+ # TODO: specify new order statuses
+ return self
class Order(models.Model):
@@ -93,9 +90,6 @@ class Order(models.Model):
self.token = str(uuid4())
return super().save(*args, **kwargs)
- def get_lines(self):
- return OrderLine.objects.filter(delivery_group__order=self)
-
def is_fully_paid(self):
total_paid = sum(
[
@@ -166,71 +160,8 @@ class Order(models.Model):
def can_cancel(self):
return self.status == OrderStatus.OPEN
-
-class DeliveryGroup(models.Model):
- """Represents a single shipment.
-
- A single order can consist of multiple shipment groups.
- """
-
- status = FSMField(
- max_length=32, default=GroupStatus.NEW, choices=GroupStatus.CHOICES,
- protected=True)
- order = models.ForeignKey(
- Order, related_name='groups', editable=False, on_delete=models.CASCADE)
- shipping_method_name = models.CharField(
- max_length=255, null=True, default=None, blank=True, editable=False)
- tracking_number = models.CharField(max_length=255, default='', blank=True)
- last_updated = models.DateTimeField(null=True, auto_now=True)
-
- def __str__(self):
- return pgettext_lazy(
- 'Shipment group str', 'Shipment #%s') % self.pk
-
- def __repr__(self):
- return '%s(%r)' % (self.__class__.__name__, list(self))
-
- def __iter__(self):
- return iter(self.lines.all())
-
- @transition(
- field=status, source=GroupStatus.NEW, target=GroupStatus.NEW)
- def process(self, cart_lines, discounts=None):
- process_delivery_group(self, cart_lines, discounts)
-
- @transition(
- field=status, source=GroupStatus.NEW, target=GroupStatus.SHIPPED)
- def ship(self, tracking_number=''):
- ship_delivery_group(self, tracking_number)
-
- @transition(
- field=status,
- source=[GroupStatus.NEW, GroupStatus.SHIPPED],
- target=GroupStatus.CANCELLED)
- def cancel(self):
- cancel_delivery_group(self)
-
- def get_total_quantity(self):
- return sum([line.quantity for line in self])
-
- def is_shipping_required(self):
- return any([line.is_shipping_required for line in self.lines.all()])
-
- def can_ship(self):
- return self.is_shipping_required() and self.status == GroupStatus.NEW
-
- def can_cancel(self):
- return self.status != GroupStatus.CANCELLED
-
def can_edit_lines(self):
- return self.status not in {GroupStatus.CANCELLED, GroupStatus.SHIPPED}
-
- def get_total(self):
- subtotals = [line.get_total() for line in self]
- if not subtotals:
- raise AttributeError(
- 'Calling get_total() on an empty shipment group')
- return sum(subtotals[1:], subtotals[0])
+ return self.status == OrderStatus.OPEN
class OrderLine(models.Model):
@@ -316,7 +247,7 @@ class Payment(BasePayment):
quantity=line.quantity,
price=line.unit_price_gross.quantize(Decimal('0.01')).amount,
currency=line.unit_price.currency)
- for line in self.order.get_lines()]
+ for line in self.order]
voucher = self.order.voucher
if voucher is not None:
diff --git a/saleor/order/transitions.py b/saleor/order/transitions.py
deleted file mode 100644
index c06c117b59..0000000000
--- a/saleor/order/transitions.py
+++ /dev/null
@@ -1,32 +0,0 @@
-from saleor.order import GroupStatus
-from saleor.order.utils import add_variant_to_delivery_group
-from saleor.product.utils import (
- deallocate_stock, decrease_stock, increase_stock)
-
-
-def process_delivery_group(group, cart_lines, discounts=None):
- """Fill shipment group with order lines created from partition items."""
- for line in cart_lines:
- add_variant_to_delivery_group(
- group, line.variant, line.quantity, discounts,
- add_to_existing=False)
-
-
-def cancel_delivery_group(group):
- """Cancel delivery group and return products to stock."""
- if group.status == GroupStatus.NEW:
- for line in group:
- if line.stock:
- deallocate_stock(line.stock, line.quantity)
- elif group.status == GroupStatus.SHIPPED:
- for line in group:
- if line.stock:
- increase_stock(line.stock, line.quantity)
-
-
-def ship_delivery_group(group, tracking_number=''):
- """Ship delivery group and decrease stock levels."""
- for line in group.lines.all():
- if line.stock:
- decrease_stock(line.stock, line.quantity)
- group.tracking_number = tracking_number
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 4521986a41..99eabd13a0 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -9,8 +9,7 @@ from prices import Money, TaxedMoney, fixed_discount
from . import GroupStatus
from ..account.utils import store_user_address
from ..core.exceptions import InsufficientStock
-from ..core.utils import ZERO_TAXED_MONEY
-from ..product.utils import allocate_stock
+from ..product.utils import allocate_stock, deallocate_stock
def check_order_status(func):
@@ -34,17 +33,17 @@ def check_order_status(func):
def cancel_order(order):
- """Cancel order by cancelling all associated shipment groups."""
- for group in order.groups.all():
- group.cancel()
- group.save()
+ """Cancel order by deallocating stock for all order lines."""
+ for line in order:
+ if line.stock:
+ deallocate_stock(line.stock, line.quantity)
def recalculate_order(order):
"""Recalculate and assign total price of order.
- Total price is a sum of items in shipment groups and order shipping price
- minus discount amount.
+ Total price is a sum of items in order and order shipping price minus
+ discount amount.
"""
prices = [line.get_total() for line in order]
total = sum(prices, order.shipping_price)
@@ -63,49 +62,8 @@ def attach_order_to_user(order, user):
order.save(update_fields=['user'])
-def add_variant_to_delivery_group(
- group, variant, total_quantity, discounts=None, add_to_existing=True):
- """Add total_quantity of variant to group.
-
- Raises InsufficientStock exception if quantity could not be fulfilled.
-
- By default, first adds variant to existing lines with same variant.
- It can be disabled with setting add_to_existing to False.
-
- Order lines are created by increasing quantity of lines,
- as long as total_quantity of variant will be added.
- """
- quantity_left = (
- add_variant_to_existing_lines(group, variant, total_quantity)
- if add_to_existing else total_quantity)
- price = variant.get_price_per_item(discounts)
- while quantity_left > 0:
- stock = variant.select_stockrecord()
- if not stock:
- raise InsufficientStock(variant)
- quantity = (
- stock.quantity_available
- if quantity_left > stock.quantity_available
- else quantity_left
- )
- group.lines.create(
- product=variant.product,
- product_name=variant.display_product(),
- product_sku=variant.sku,
- is_shipping_required=(
- variant.product.product_type.is_shipping_required),
- quantity=quantity,
- unit_price=price,
- stock=stock,
- stock_location=stock.location.name)
- allocate_stock(stock, quantity)
- # refresh stock for accessing quantity_allocated
- stock.refresh_from_db()
- quantity_left -= quantity
-
-
def add_variant_to_order(order, variant, total_quantity, discounts=None):
- """Add total_quantity of variant to group.
+ """Add total_quantity of variant to order.
Raises InsufficientStock exception if quantity could not be fulfilled.
@@ -134,8 +92,7 @@ def add_variant_to_order(order, variant, total_quantity, discounts=None):
is_shipping_required=(
variant.product.product_type.is_shipping_required),
quantity=quantity,
- unit_price_net=price.net,
- unit_price_gross=price.gross,
+ unit_price=price,
stock=stock,
stock_location=stock.location.name)
allocate_stock(stock, quantity)
@@ -175,11 +132,11 @@ def add_variant_to_existing_lines(order, variant, total_quantity):
def merge_duplicates_into_order_line(line):
- """Merge duplicated lines in shipment group into one (given) line.
+ """Merge duplicated lines in order into one (given) line.
If there are no duplicates, nothing will happen.
"""
- lines = line.delivery_group.lines.filter(
+ lines = line.order.lines.filter(
product=line.product, product_name=line.product_name,
product_sku=line.product_sku, stock=line.stock,
is_shipping_required=line.is_shipping_required)
@@ -192,58 +149,9 @@ def merge_duplicates_into_order_line(line):
def change_order_line_quantity(line, new_quantity):
"""Change the quantity of ordered items in a order line."""
line.quantity = new_quantity
- line.save()
+ order = line.order
- if not line.delivery_group.get_total_quantity():
- line.delivery_group.delete()
- order = line.delivery_group.order
- if not order.get_lines():
- order.history.create(
- content=pgettext_lazy(
- 'Order status history entry',
- 'Order cancelled. No items in order'))
-
-
-def remove_empty_groups(line, force=False):
- """Remove order line and associated shipment group and order.
-
- Remove is done only if quantity of order line or items in group or in order
- is equal to 0.
- """
- source_group = line.delivery_group
- order = source_group.order
if line.quantity:
line.save()
else:
line.delete()
- if not source_group.get_total_quantity() or force:
- source_group.delete()
- if not order.get_lines():
- order.history.create(
- content=pgettext_lazy(
- 'Order status history entry',
- 'Order cancelled. No items in order'))
-
-
-def move_order_line_to_group(line, target_group, quantity):
- from .models import OrderLine
- """Split given quantity of order line to another shipment group."""
- try:
- target_line = target_group.lines.get(
- product=line.product, product_name=line.product_name,
- product_sku=line.product_sku, stock=line.stock,
- is_shipping_required=line.is_shipping_required)
- except OrderLine.DoesNotExist:
- target_group.lines.create(
- delivery_group=target_group, product=line.product,
- product_name=line.product_name, product_sku=line.product_sku,
- is_shipping_required=line.is_shipping_required,
- quantity=quantity, unit_price_net=line.unit_price_net,
- stock=line.stock,
- stock_location=line.stock_location,
- unit_price_gross=line.unit_price_gross)
- else:
- target_line.quantity += quantity
- target_line.save()
- line.quantity -= quantity
- remove_empty_groups(line)
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 6a55b6206e..b7a6087785 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -27,9 +27,8 @@ def details(request, token):
orders = orders.select_related(
'billing_address', 'shipping_address', 'user')
order = get_object_or_404(orders, token=token)
- groups = order.groups.all()
notes = order.notes.filter(is_public=True)
- ctx = {'order': order, 'groups': groups, 'notes': notes}
+ ctx = {'order': order, 'notes': notes}
if order.status == OrderStatus.OPEN:
user = request.user if request.user.is_authenticated else None
note = OrderNote(order=order, user=user)
@@ -47,7 +46,6 @@ def payment(request, token):
orders = orders.select_related(
'billing_address', 'shipping_address', 'user')
order = get_object_or_404(orders, token=token)
- groups = order.groups.all()
payments = order.payments.all()
form_data = request.POST or None
try:
@@ -70,8 +68,8 @@ def payment(request, token):
return redirect(
'order:payment', token=order.token, variant=payment_method)
ctx = {
- 'order': order, 'groups': groups, 'payment_form': payment_form,
- 'payments': payments, 'waiting_payment': waiting_payment,
+ 'order': order, 'payment_form': payment_form, 'payments': payments,
+ 'waiting_payment': waiting_payment,
'waiting_payment_form': waiting_payment_form}
return TemplateResponse(request, 'order/payment.html', ctx)
diff --git a/templates/dashboard/order/detail.html b/templates/dashboard/order/detail.html
index 1a9261a678..c38425b6a8 100644
--- a/templates/dashboard/order/detail.html
+++ b/templates/dashboard/order/detail.html
@@ -294,7 +294,7 @@
{{ line.unit_price.gross|amount:'html' }}
</td>
<td class="right-align">
- {% if group.can_edit_lines %}
+ {% if order.can_edit_lines %}
<a class="dropdown-button" href="#" data-activates="line-actions-{{ line.pk }}" data-constrainwidth="false">
{{ line.quantity }} {% if line.stock_location and is_many_stock_locations %} ({{ line.stock_location|truncatechars:10 }}) {% endif %}
<svg data-src="{% static "dashboard/images/arrow-drop-down.svg" %}" width="24" height="24" />
@@ -311,6 +311,12 @@
{% trans "Change stock" context "Order table row action" %}
</a>
</li>
+ {% endif %}
+ <li>
+ <a href="#base-modal" data-href="{% url 'dashboard:orderline-cancel' order_pk=order.pk line_pk=line.pk %}" class="modal-trigger-custom" title="{% trans "Remove line" context "Order table row action" %}">
+ {% trans "Remove line" context "Order table row action" %}
+ </a>
+ </li>
</ul>
{% else %}
{{ line.quantity }}
@@ -326,26 +332,12 @@
</div>
{% if perms.order.edit_order and order.is_open %}
<div class="data-table-action">
- {% if false %}
- {% if group.can_ship %}
- <a href="#base-modal" data-href="{% url 'dashboard:ship-delivery-group' order_pk=order.pk group_pk=group.pk %}" class="btn-flat waves-effect modal-trigger-custom">
- {% trans "Dispatch" context "Shipment group table action" %}
- </a>
- {% endif %}
- {% if group.can_cancel %}
- <a href="#base-modal" data-href="{% url 'dashboard:cancel-delivery-group' order_pk=order.pk group_pk=group.pk %}" class="btn-flat waves-effect modal-trigger-custom" title="{% trans 'Cancel group' context 'Shipment group table action' %}">
- {% trans "Cancel shipment" context "Shipment group table action" %}
- </a>
- {% endif %}
- {% endif %}
<a href="#base-modal" data-href="{% url 'dashboard:add-variant-to-order' order_pk=order.pk %}" class="btn-flat waves-effect modal-trigger-custom" title="{% trans "Add product to order" context "Order summary card action title" %}">
{% trans "Add product" context "Order summary card action" %}
</a>
- {% if false %}
- <a href="{% url 'dashboard:order-packing-slips' group_pk=group.pk %}" data-href="" class="btn-flat waves-effect" target="_blank">
- {% trans "Packing Slips" context "Order detail action" %}
- </a>
- {% endif %}
+ <a href="{% url 'dashboard:order-packing-slips' order_pk=order.pk %}" data-href="" class="btn-flat waves-effect" target="_blank">
+ {% trans "Packing Slips" context "Order detail action" %}
+ </a>
</div>
{% endif %}
</div>
@@ -420,10 +412,10 @@
<thead>
<tr>
<th class="wide">
- {% trans "Item" context "Shipment group table header" %}
+ {% trans "Item" context "Order table header" %}
</th>
<th class="right-align">
- {% trans "Quantity" context "Shipment group table header" %}
+ {% trans "Quantity" context "Order table header" %}
</th>
</tr>
</thead>
diff --git a/templates/dashboard/order/modal/add_variant_to_group.html b/templates/dashboard/order/modal/add_variant_to_order.html
similarity index 85%
rename from templates/dashboard/order/modal/add_variant_to_group.html
rename to templates/dashboard/order/modal/add_variant_to_order.html
index a81e349e47..643b78f25f 100644
--- a/templates/dashboard/order/modal/add_variant_to_group.html
+++ b/templates/dashboard/order/modal/add_variant_to_order.html
@@ -8,7 +8,7 @@
{% endblock %}
{% block title %}
-{% blocktrans trimmed with shipment=group context "Modal order add variant title" %}
+{% blocktrans trimmed with order=order context "Modal order add variant title" %}
Add product to {{ order }}
{% endblocktrans %}
{% endblock %}
diff --git a/templates/dashboard/order/modal/cancel_shipment_group.html b/templates/dashboard/order/modal/cancel_shipment_group.html
deleted file mode 100644
index 6b861c6a0f..0000000000
--- a/templates/dashboard/order/modal/cancel_shipment_group.html
+++ /dev/null
@@ -1,27 +0,0 @@
-{% extends "dashboard/base_modal.html" %}
-
-{% load i18n %}
-
-{% block action_url %}
-{% url 'dashboard:cancel-delivery-group' order_pk=order.pk group_pk=group.pk %}
-{% endblock %}
-
-{% block title %}
-{% trans "Cancel shipment group?" context "Modal cancel shipment group title" %}
-{% endblock %}
-
-{% block content %}
- <div class="col s12">
- {% blocktrans trimmed with shipment=group context "Modal cancel shipment group text" %}
- After this action {{ shipment }} will be cancelled. Ordered items will be returned to stock.
- {% endblocktrans %}
- </div>
-{% endblock %}
-
-{% block cancel_action %}
-{% trans "Abort" context "Dashboard abort action" %}
-{% endblock %}
-
-{% block primary_action %}
-{% trans "Cancel this shipment" context "Modal cancel shipment group primary action" %}
-{% endblock %}
diff --git a/templates/dashboard/order/modal/shipment_group_stock.html b/templates/dashboard/order/modal/order_line_stock.html
similarity index 100%
rename from templates/dashboard/order/modal/shipment_group_stock.html
rename to templates/dashboard/order/modal/order_line_stock.html
diff --git a/templates/dashboard/order/modal/ship_shipment_group.html b/templates/dashboard/order/modal/ship_shipment_group.html
deleted file mode 100644
index e8bfe08ef4..0000000000
--- a/templates/dashboard/order/modal/ship_shipment_group.html
+++ /dev/null
@@ -1,25 +0,0 @@
-{% extends "dashboard/base_modal.html" %}
-
-{% load i18n %}
-{% load i18n_address_tags %}
-{% load materializecss %}
-
-{% block action_url %}
-{% url 'dashboard:ship-delivery-group' order_pk=order.pk group_pk=group.pk %}
-{% endblock %}
-
-{% block title %}
-{% trans "Dispatch shipment group" context "Modal ship shipment group title" %}
-{% endblock %}
-
-{% block content %}
- <div class="col s12">
- {% trans "Dispatch this shipment to the following address:" context "Modal ship shipment group text" %}
- <div class="address">{% format_address order.shipping_address %}</div>
- </div>
-{{ form|materializecss }}
-{% endblock %}
-
-{% block primary_action %}
-{% trans "Ship" context "Modal ship shipment group primary action" %}
-{% endblock %}
diff --git a/templates/dashboard/order/modal/split_order_line.html b/templates/dashboard/order/modal/split_order_line.html
deleted file mode 100644
index bb22267890..0000000000
--- a/templates/dashboard/order/modal/split_order_line.html
+++ /dev/null
@@ -1,20 +0,0 @@
-{% extends "dashboard/base_modal.html" %}
-
-{% load i18n %}
-{% load materializecss %}
-
-{% block action_url %}
-{% url 'dashboard:orderline-split' order_pk=order.pk line_pk=line_pk %}
-{% endblock %}
-
-{% block title %}
-{% trans "Split order line" context "Modal split order line title" %}
-{% endblock %}
-
-{% block content %}
-{{ form|materializecss:"s12 m6" }}
-{% endblock %}
-
-{% block primary_action %}
-{% trans "Split" context "Modal split order line primary action" %}
-{% endblock %}
diff --git a/templates/dashboard/order/pdf/invoice.html b/templates/dashboard/order/pdf/invoice.html
index 443e134fa4..025e3d4f54 100644
--- a/templates/dashboard/order/pdf/invoice.html
+++ b/templates/dashboard/order/pdf/invoice.html
@@ -81,36 +81,34 @@
</tr>
</thead>
<tbody>
- {% for item in order.get_lines.all %}
+ {% for line in order %}
<tr>
<td>
- {{ item.product_name|truncatechars:30 }}<br>
+ {{ line.product_name|truncatechars:30 }}<br>
</td>
<td>
- {{ item.product_sku }}
+ {{ line.product_sku }}
</td>
<td class="right-align">
- {{ item.unit_price.gross|amount:'html' }}
+ {{ line.unit_price.gross|amount:'html' }}
</td>
<td class="right-align">
- {{ item.quantity }}
+ {{ line.quantity }}
</td>
<td class="right-align">
- {{ item.get_total.gross|amount:'html' }}
+ {{ line.get_total.gross|amount:'html' }}
</td>
</tr>
{% endfor %}
{% if order.shipping_price.gross or order.is_shipping_required %}
- {% for shipping in shipping_methods %}
- <tr>
- <td>
- {% trans "Shipping" context "Shipment order table item column data" %}
- </td>
- <td colspan="3">
- {{ shipping.name }}
- </td>
- </tr>
- {% endfor %}
+ <tr>
+ <td>
+ {% trans "Shipping" context "Shipment order table item column data" %}
+ </td>
+ <td colspan="3">
+ {{ order.shipping_method_name }}
+ </td>
+ </tr>
{% endif %}
</tbody>
</table>
diff --git a/templates/dashboard/order/pdf/packing_slip.html b/templates/dashboard/order/pdf/packing_slip.html
index 299aa64196..66913df979 100644
--- a/templates/dashboard/order/pdf/packing_slip.html
+++ b/templates/dashboard/order/pdf/packing_slip.html
@@ -14,7 +14,7 @@
<img src="{% static '/images/logo-document.svg' %}">
</div>
<div
- style="float:right">{{ group.order.created }}<br>{% trans "Order ID:" context "Packing slip header" %} {{ group.order.id }}
+ style="float:right">{{ order.created }}<br>{% trans "Order ID:" context "Packing slip header" %} {{ order.id }}
</div>
</header>
@@ -22,21 +22,21 @@
<table width="100%" border="1" cellspacing="0">
<thead>
<tr>
- {% if group.order.shipping_address %}
+ {% if order.shipping_address %}
<th align="left" width="50%">
{% trans "Shipping Details" context "Packing slip shipping details" %}
</th>
{% endif %}
- <th align="left"{% if group.order.shipping_address %} width="50%"{% endif %}>
+ <th align="left"{% if order.shipping_address %} width="50%"{% endif %}>
{% trans "Billing Details" context "Packing slip shipping details" %}
</th>
</tr>
</thead>
<tbody>
<tr>
- {% if group.order.shipping_address %}
+ {% if order.shipping_address %}
<td valign="top">
- {% with group.order.shipping_address as address %}
+ {% with order.shipping_address as address %}
<h2>
{% trans "Shipping address" context "Packing slip shipping address" %}
</h2>
@@ -45,7 +45,7 @@
</td>
{% endif %}
<td valign="top">
- {% with group.order.billing_address as address %}
+ {% with order.billing_address as address %}
<h2>
{% trans "Billing address" context "Packing slip billing address" %}
</h2>
@@ -57,23 +57,23 @@
</table>
<h2>{% trans "Items Ordered" context "Order invoice" %}</h2>
-{% if group %}
+{% if order %}
<table class="bordered data-table">
<thead>
<tr>
<th class="wide">
- {% trans "Item" context "Shipment group table header" %}
+ {% trans "Item" context "Order table header" %}
</th>
<th>
- {% trans "SKU" context "Shipment group table header" %}
+ {% trans "SKU" context "Order table header" %}
</th>
<th class="right-align">
- {% trans "Quantity" context "Shipment group table header" %}
+ {% trans "Quantity" context "Order table header" %}
</th>
</tr>
</thead>
<tbody>
- {% for line in group.lines.all %}
+ {% for line in order %}
<tr>
<td>
{{ line.product_name }}<br>
diff --git a/templates/templated_email/source/order/confirm_order.email b/templates/templated_email/source/order/confirm_order.email
index ded1bed49a..449844c66f 100644
--- a/templates/templated_email/source/order/confirm_order.email
+++ b/templates/templated_email/source/order/confirm_order.email
@@ -11,9 +11,9 @@ Hi!
Thank you for your order. Below is the list of ordered products. To see your payment details please visit:
{{ url }}{% endblocktrans %}
-{% for group in order.groups.all %}{% for line in group.lines.all %}
+{% for line in order %}
{{ line.quantity }} x {{ line.product_name }}, {{ line.get_total.gross|amount }}
-{% endfor %}{% endfor %}
+{% endfor %}
{% trans "Order summary" context "Order confirmation e-mail table header" %}:
{% trans "Subtotal" context "Order confirmation e-mail table header" %}: {{ order.get_subtotal.gross|amount }}
{% trans "Shipping" context "Order confirmation e-mail table header" %}: {{ order.shipping_price.gross|amount }}
diff --git a/templates/templated_email/source/order/partials/_order_lines.mjml b/templates/templated_email/source/order/partials/_order_lines.mjml
index 93a71de535..84333b2fc5 100644
--- a/templates/templated_email/source/order/partials/_order_lines.mjml
+++ b/templates/templated_email/source/order/partials/_order_lines.mjml
@@ -43,17 +43,15 @@
</tr>
</thead>
<tbody>
- {% for group in order.groups.all %}
- {% for line in group.lines.all %}
- <tr class="table-item-row">
- <td>{{ line.product_name }}</td>
- <td style="text-align: right;">{{ line.quantity }}</td>
- <td style="text-align: right;">
- {{ line.unit_price.gross|amount:'html' }}
- </td>
- <td style="text-align: right;">{{ line.get_total.gross|amount }}</td>
- </tr>
- {% endfor %}
+ {% for line in order %}
+ <tr class="table-item-row">
+ <td>{{ line.product_name }}</td>
+ <td style="text-align: right;">{{ line.quantity }}</td>
+ <td style="text-align: right;">
+ {{ line.unit_price.gross|amount:'html' }}
+ </td>
+ <td style="text-align: right;">{{ line.get_total.gross|amount }}</td>
+ </tr>
{% endfor %}
</tbody>
</mj-table>
diff --git a/tests/conftest.py b/tests/conftest.py
index 6b2399ab33..0fc03d4266 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -16,8 +16,7 @@ from saleor.cart import utils
from saleor.cart.models import Cart
from saleor.checkout.core import Checkout
from saleor.discount.models import Sale, Voucher
-from saleor.order import GroupStatus
-from saleor.order.models import DeliveryGroup, Order, OrderLine
+from saleor.order.models import Fulfillment, Order, OrderLine
from saleor.order.utils import recalculate_order
from saleor.page.models import Page
from saleor.product.models import (
@@ -373,13 +372,11 @@ def voucher(db): # pylint: disable=W0613
@pytest.fixture()
def order_with_lines(order, product_type, default_category):
- group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
name='Test product', price=Money('10.00', 'USD'),
product_type=product_type, category=default_category)
- OrderLine.objects.create(
- delivery_group=group,
+ order.lines.create(
product=product,
product_name=product.name,
product_sku='SKU_%d' % (product.pk,),
@@ -391,8 +388,7 @@ def order_with_lines(order, product_type, default_category):
name='Test product 2', price=Money('20.00', 'USD'),
product_type=product_type, category=default_category)
- OrderLine.objects.create(
- delivery_group=group,
+ order.lines.create(
product=product,
product_name=product.name,
product_sku='SKU_%d' % (product.pk,),
@@ -404,8 +400,7 @@ def order_with_lines(order, product_type, default_category):
name='Test product 3', price=Money('30.00', 'USD'),
product_type=product_type, category=default_category)
- OrderLine.objects.create(
- delivery_group=group,
+ order.lines.create(
product=product,
product_name=product.name,
product_sku='SKU_%d' % (product.pk,),
@@ -420,7 +415,6 @@ def order_with_lines(order, product_type, default_category):
@pytest.fixture()
def order_with_lines_and_stock(order, product_type, default_category):
- group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
name='Test product', price=Money('10.00', 'USD'),
product_type=product_type, category=default_category)
@@ -429,8 +423,8 @@ def order_with_lines_and_stock(order, product_type, default_category):
stock = Stock.objects.create(
variant=variant, cost_price=Money(1, 'USD'), quantity=5,
quantity_allocated=3, location=warehouse)
- OrderLine.objects.create(
- delivery_group=group,
+ order.lines.create(
+ order=order,
product=product,
product_name=product.name,
product_sku='SKU_A',
@@ -447,8 +441,8 @@ def order_with_lines_and_stock(order, product_type, default_category):
stock = Stock.objects.create(
variant=variant, cost_price=Money(2, 'USD'), quantity=2,
quantity_allocated=2, location=warehouse)
- OrderLine.objects.create(
- delivery_group=group,
+ order.lines.create(
+ order=order,
product=product,
product_name=product.name,
product_sku='SKU_B',
@@ -471,8 +465,8 @@ def order_with_variant_from_different_stocks(order_with_lines_and_stock):
stock = Stock.objects.create(
variant=variant, cost_price=Money(1, 'USD'), quantity=5,
quantity_allocated=2, location=warehouse_2)
- OrderLine.objects.create(
- delivery_group=line.delivery_group,
+ order_with_lines_and_stock.lines.create(
+ order=order,
product=variant.product,
product_name=variant.product.name,
product_sku=line.product_sku,
@@ -489,33 +483,6 @@ def order_with_variant_from_different_stocks(order_with_lines_and_stock):
return order_with_lines_and_stock
-def delivery_group(order, product_type, default_category):
- group = DeliveryGroup.objects.create(order=order)
- product = Product.objects.create(
- name='Test product', price=Money('10.00', 'USD'),
- product_type=product_type, category=default_category)
- variant = ProductVariant.objects.create(product=product, sku='SKU_A')
- warehouse = StockLocation.objects.create(name='Warehouse 2')
- stock = Stock.objects.create(
- variant=variant, cost_price=Money(1, 'USD'), quantity=5,
- quantity_allocated=3, location=warehouse)
- OrderLine.objects.create(
- delivery_group=group,
- product=product,
- product_name=product.name,
- product_sku='SKU_A',
- is_shipping_required=product.product_type.is_shipping_required,
- quantity=3,
- unit_price_net=Decimal('30.00'),
- unit_price_gross=Decimal('30.00'),
- stock=stock,
- stock_location=stock.location.name)
- recalculate_order(order)
- order.refresh_from_db()
- return group
-
-
@pytest.fixture()
def sale(db, default_category):
sale = Sale.objects.create(name="Sale", value=5)
@@ -592,51 +559,34 @@ def permission_impersonate_user():
@pytest.fixture
def open_orders(billing_address):
- def group_data(orders, status):
- return {'order': orders[-1], 'status': status}
-
- orders = []
-
- orders.append(Order.objects.create(billing_address=billing_address))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
-
- orders.append(Order.objects.create(billing_address=billing_address))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
+ order_1 = Order.objects.create(billing_address=billing_address)
+ order_1.lines.create(
+ quantity=2, unit_price_net=Decimal('10.00'),
+ unit_price_gross=Decimal('10.00'), is_shipping_required=True)
- orders.append(Order.objects.create(billing_address=billing_address))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
+ order_2 = Order.objects.create(billing_address=billing_address)
+ line = order_2.lines.create(
+ quantity=2, unit_price_net=Decimal('10.00'),
+ unit_price_gross=Decimal('10.00'), is_shipping_required=True)
+ fulfillment = Fulfillment.objects.create(order=order_2)
+ fulfillment.lines.create(order_line=line, quantity=1)
- orders.append(Order.objects.create(billing_address=billing_address))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
-
- return orders
+ return [order_1, order_2]
@pytest.fixture
def closed_orders(billing_address):
- def group_data(orders, status):
- return {'order': orders[-1], 'status': status}
-
- orders = []
-
- orders.append(Order.objects.create(billing_address=billing_address))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
-
- orders.append(Order.objects.create(billing_address=billing_address))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
-
- orders.append(Order.objects.create(billing_address=billing_address))
- DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
-
# empty order is considered as closed
- orders.append(Order.objects.create(billing_address=billing_address))
+ order_1 = Order.objects.create(billing_address=billing_address)
+
+ order_2 = Order.objects.create(billing_address=billing_address)
+ line = order_2.lines.create(
+ quantity=2, unit_price_net=Decimal('10.00'),
+ unit_price_gross=Decimal('10.00'), is_shipping_required=True)
+ fulfillment = Fulfillment.objects.create(order=order_2)
+ fulfillment.lines.create(order_line=line, quantity=2)
- return orders
+ return [order_1, order_2]
@pytest.fixture
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index 3b013aaad5..0102c07241 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -3,20 +3,16 @@ from unittest.mock import patch
import pytest
from django.urls import reverse
-from django_fsm import TransitionNotAllowed
from payments import FraudStatus, PaymentStatus
from prices import Money, TaxedMoney
from tests.utils import get_redirect_location, get_url_path
-from saleor.cart.models import Cart
from saleor.dashboard.order.forms import ChangeQuantityForm, OrderNoteForm
-from saleor.order import GroupStatus
-from saleor.order.models import (
- DeliveryGroup, Order, OrderHistoryEntry, OrderLine, OrderNote)
+from saleor.order.models import Order, OrderHistoryEntry, OrderLine, OrderNote
from saleor.order.utils import (
add_variant_to_existing_lines, add_variant_to_order,
- change_order_line_quantity, remove_empty_groups)
+ change_order_line_quantity)
from saleor.product.models import ProductVariant, Stock, StockLocation
@@ -68,7 +64,7 @@ def test_view_refund_order_payment(admin_client, order_with_lines_and_stock):
@pytest.mark.integration
@pytest.mark.django_db
def test_view_cancel_order_line(admin_client, order_with_lines_and_stock):
- lines_before = order_with_lines_and_stock.get_lines()
+ lines_before = order_with_lines_and_stock.lines.all()
lines_before_count = lines_before.count()
line = lines_before.first()
line_quantity = line.quantity
@@ -87,7 +83,7 @@ def test_view_cancel_order_line(admin_client, order_with_lines_and_stock):
assert get_redirect_location(response) == reverse(
'dashboard:order-details', args=[order_with_lines_and_stock.pk])
# check ordered item removal
- lines_after = Order.objects.get().get_lines()
+ lines_after = Order.objects.get().lines.all()
assert lines_before_count - 1 == lines_after.count()
# check stock deallocation
assert Stock.objects.first().quantity_allocated == (
@@ -102,9 +98,7 @@ def test_view_cancel_order_line(admin_client, order_with_lines_and_stock):
'line_pk': OrderLine.objects.get().pk})
response = admin_client.post(
url, {'csrfmiddlewaretoken': 'hello'}, follow=True)
- # check shipment group removal if it becomes empty
- assert Order.objects.get().get_lines().count() == 0
- assert DeliveryGroup.objects.count() == 0
+ assert Order.objects.get().lines.all().count() == 0
# check success messages after redirect
assert response.context['messages']
@@ -113,7 +107,7 @@ def test_view_cancel_order_line(admin_client, order_with_lines_and_stock):
@pytest.mark.django_db
def test_view_change_order_line_quantity(
admin_client, order_with_lines_and_stock):
- lines_before_quantity_change = order_with_lines_and_stock.get_lines()
+ lines_before_quantity_change = order_with_lines_and_stock.lines.all()
lines_before_quantity_change_count = lines_before_quantity_change.count()
line = lines_before_quantity_change.first()
line_quantity_before_quantity_change = line.quantity
@@ -134,7 +128,7 @@ def test_view_change_order_line_quantity(
args=[order_with_lines_and_stock.pk])
# success messages should appear after redirect
assert response.context['messages']
- lines_after = Order.objects.get().get_lines()
+ lines_after = Order.objects.get().lines.all()
# order should have the same lines
assert lines_before_quantity_change_count == lines_after.count()
# stock allocation should be 2 now
@@ -142,8 +136,6 @@ def test_view_change_order_line_quantity(
line.refresh_from_db()
# source line quantity should be decreased to 2
assert line.quantity == 2
- # order should have the same shipment groups count
- assert order_with_lines_and_stock.groups.count() == 1
# a note in the order's history should be created
assert OrderHistoryEntry.objects.get(
order=order_with_lines_and_stock).content == (
@@ -158,7 +150,7 @@ def test_view_change_order_line_quantity(
@pytest.mark.django_db
def test_view_change_order_line_quantity_with_invalid_data(
admin_client, order_with_lines_and_stock):
- lines = order_with_lines_and_stock.get_lines()
+ lines = order_with_lines_and_stock.lines.all()
line = lines.first()
url = reverse(
'dashboard:orderline-change-quantity', kwargs={
@@ -171,10 +163,9 @@ def test_view_change_order_line_quantity_with_invalid_data(
def test_dashboard_change_quantity_form(request_cart_with_item, order):
cart = request_cart_with_item
- group = DeliveryGroup.objects.create(order=order)
for line in cart.lines.all():
add_variant_to_order(order, line.variant, line.quantity)
- order_line = group.lines.get()
+ order_line = order.lines.get()
# Check max quantity validation
form = ChangeQuantityForm({'quantity': 9999}, instance=order_line)
@@ -185,12 +176,12 @@ def test_dashboard_change_quantity_form(request_cart_with_item, order):
# Check minimum quantity validation
form = ChangeQuantityForm({'quantity': 0}, instance=order_line)
assert not form.is_valid()
- assert group.lines.get().stock.quantity_allocated == 1
+ assert order.lines.get().stock.quantity_allocated == 1
# Check available quantity validation
form = ChangeQuantityForm({'quantity': 20}, instance=order_line)
assert not form.is_valid()
- assert group.lines.get().stock.quantity_allocated == 1
+ assert order.lines.get().stock.quantity_allocated == 1
assert form.errors['quantity'] == ['Only 5 remaining in stock.']
# Save same quantity
@@ -198,128 +189,28 @@ def test_dashboard_change_quantity_form(request_cart_with_item, order):
assert form.is_valid()
form.save()
order_line.stock.refresh_from_db()
- assert group.lines.get().stock.quantity_allocated == 1
+ assert order.lines.get().stock.quantity_allocated == 1
# Increase quantity
form = ChangeQuantityForm({'quantity': 2}, instance=order_line)
assert form.is_valid()
form.save()
order_line.stock.refresh_from_db()
- assert group.lines.get().stock.quantity_allocated == 2
+ assert order.lines.get().stock.quantity_allocated == 2
# Decrease quantity
form = ChangeQuantityForm({'quantity': 1}, instance=order_line)
assert form.is_valid()
form.save()
- assert group.lines.get().stock.quantity_allocated == 1
-
-
-def test_view_split_order_line(admin_client, order_with_lines_and_stock):
- lines_before_split = order_with_lines_and_stock.get_lines()
- lines_before_split_count = lines_before_split.count()
- line = lines_before_split.first()
- line_quantity_before_split = line.quantity
- quantity_allocated_before_split = line.stock.quantity_allocated
- old_delivery_group = DeliveryGroup.objects.get()
-
- url = reverse(
- 'dashboard:orderline-split', kwargs={
- 'order_pk': order_with_lines_and_stock.pk,
- 'line_pk': line.pk})
- response = admin_client.get(url)
- assert response.status_code == 200
- response = admin_client.post(
- url,
- {'quantity': 2, 'target_group': ''},
- follow=True)
- redirected_to, redirect_status_code = response.redirect_chain[-1]
- # check redirection
- assert redirect_status_code == 302
- assert get_url_path(redirected_to) == reverse(
- 'dashboard:order-details',
- args=[order_with_lines_and_stock.pk])
- # success messages should appear after redirect
- assert response.context['messages']
- lines_after = Order.objects.get().get_lines()
- # order should have one more line
- assert lines_before_split_count + 1 == lines_after.count()
- # stock allocation should not be changed
- assert Stock.objects.first().quantity_allocated == (
- quantity_allocated_before_split)
- line.refresh_from_db()
- # source line quantity should be decreased to 1
- assert line.quantity == line_quantity_before_split - 2
- # order should have 2 shipment groups now
- assert order_with_lines_and_stock.groups.count() == 2
- # a note in the order's history should be created
- new_group = DeliveryGroup.objects.last()
- assert OrderHistoryEntry.objects.get(
- order=order_with_lines_and_stock).content == (
- 'Moved 2 items %(item)s from '
- '%(old_group)s to %(new_group)s') % {
- 'item': line,
- 'old_group': old_delivery_group,
- 'new_group': new_group}
- new_line = new_group.lines.get()
- # the new line should contain the moved quantity
- assert new_line.quantity == 2
- url = reverse(
- 'dashboard:orderline-split', kwargs={
- 'order_pk': order_with_lines_and_stock.pk,
- 'line_pk': new_line.pk})
- admin_client.post(
- url, {'quantity': 2, 'target_group': old_delivery_group.pk})
- # an other note in the order's history should be created
- assert OrderHistoryEntry.objects.filter(
- order=order_with_lines_and_stock).last().content == (
- 'Moved 2 items %(item)s from removed '
- 'group to %(new_group)s') % {
- 'item': line,
- 'new_group': old_delivery_group}
- # the new shipment should be removed
- assert order_with_lines_and_stock.groups.count() == 1
- # the related order line should be removed
- assert lines_before_split_count == Order.objects.get().get_lines().count()
- line.refresh_from_db()
- # the initial line should get the quantity restored to its initial value
- assert line_quantity_before_split == line.quantity
-
-
[email protected]('quantity', [0, 4])
-def test_view_split_order_line_with_invalid_data(
- admin_client, order_with_lines_and_stock, quantity):
- lines = order_with_lines_and_stock.get_lines()
- line = lines.first()
- url = reverse(
- 'dashboard:orderline-split', kwargs={
- 'order_pk': order_with_lines_and_stock.pk,
- 'line_pk': line.pk})
- response = admin_client.post(
- url, {'quantity': quantity, 'target_group': ''})
- assert response.status_code == 400
- assert DeliveryGroup.objects.count() == 1
+ assert order.lines.get().stock.quantity_allocated == 1
def test_ordered_item_change_quantity(transactional_db, order_with_lines):
assert list(order_with_lines.history.all()) == []
- lines = order_with_lines.groups.all()[0].lines.all()
- change_order_line_quantity(lines[0], 0)
- change_order_line_quantity(lines[1], 0)
+ lines = order_with_lines.lines.all()
change_order_line_quantity(lines[2], 0)
- history = list(order_with_lines.history.all())
- assert len(history) == 1
- assert history[0].content == 'Order cancelled. No items in order'
-
-
-def test_ordered_item_remove_empty_group_with_force(
- transactional_db, order_with_lines):
- group = order_with_lines.groups.all()[0]
- lines = group.lines.all()
- remove_empty_groups(lines[0], force=True)
+ change_order_line_quantity(lines[1], 0)
+ change_order_line_quantity(lines[0], 0)
history = list(order_with_lines.history.all())
assert len(history) == 1
assert history[0].content == 'Order cancelled. No items in order'
@@ -366,13 +257,11 @@ def test_view_order_packing_slips(
order_with_lines_and_stock.save()
url = reverse(
'dashboard:order-packing-slips', kwargs={
- 'group_pk': order_with_lines_and_stock.groups.all()[0].pk})
+ 'order_pk': order_with_lines_and_stock.pk})
response = admin_client.get(url)
assert response.status_code == 200
assert response['content-type'] == 'application/pdf'
- name = "packing-slip-%s-%s" % (
- order_with_lines_and_stock.id,
- order_with_lines_and_stock.groups.all()[0].pk)
+ name = "packing-slip-%s" % (order_with_lines_and_stock.id,)
assert response['Content-Disposition'] == 'filename=%s' % name
@@ -385,7 +274,7 @@ def test_view_order_packing_slips_without_shipping(
order_with_lines_and_stock.save()
url = reverse(
'dashboard:order-packing-slips', kwargs={
- 'group_pk': order_with_lines_and_stock.groups.all()[0].pk})
+ 'order_pk': order_with_lines_and_stock.pk})
response = admin_client.get(url)
assert response.status_code == 200
assert response['content-type'] == 'application/pdf'
@@ -396,7 +285,7 @@ def test_view_order_packing_slips_without_shipping(
def test_view_change_order_line_stock_valid(
admin_client, order_with_lines_and_stock):
order = order_with_lines_and_stock
- line = order.get_lines().last()
+ line = order.lines.last()
old_stock = line.stock
variant = ProductVariant.objects.get(sku=line.product_sku)
stock_location = StockLocation.objects.create(name='Warehouse 2')
@@ -427,7 +316,7 @@ def test_view_change_order_line_stock_valid(
def test_view_change_order_line_stock_insufficient_stock(
admin_client, order_with_lines_and_stock):
order = order_with_lines_and_stock
- line = order.get_lines().last()
+ line = order.lines.last()
old_stock = line.stock
variant = ProductVariant.objects.get(sku=line.product_sku)
stock_location = StockLocation.objects.create(name='Warehouse 2')
@@ -458,16 +347,14 @@ def test_view_change_order_line_stock_insufficient_stock(
def test_view_change_order_line_stock_merges_lines(
admin_client, order_with_lines_and_stock):
order = order_with_lines_and_stock
- line = order.get_lines().first()
- group = line.delivery_group
+ line = order.lines.first()
old_stock = line.stock
variant = ProductVariant.objects.get(sku=line.product_sku)
stock_location = StockLocation.objects.create(name='Warehouse 2')
stock = Stock.objects.create(
variant=variant, cost_price=2, quantity=2, quantity_allocated=2,
location=stock_location)
- line_2 = group.lines.create(
- delivery_group=group,
+ line_2 = order.lines.create(
product=line.product,
product_name=line.product.name,
product_sku='SKU_A',
@@ -477,7 +364,7 @@ def test_view_change_order_line_stock_merges_lines(
unit_price_gross=Decimal('30.00'),
stock=stock,
stock_location=stock.location.name)
- lines_before = group.lines.count()
+ lines_before = order.lines.count()
url = reverse(
'dashboard:orderline-change-stock', kwargs={
@@ -487,7 +374,7 @@ def test_view_change_order_line_stock_merges_lines(
response = admin_client.post(url, data)
assert response.status_code == 200
- assert group.lines.count() == lines_before - 1
+ assert order.lines.count() == lines_before - 1
old_stock.refresh_from_db()
assert old_stock.quantity_allocated == 5
@@ -499,15 +386,14 @@ def test_view_change_order_line_stock_merges_lines(
def test_add_variant_to_existing_lines_one_line(
order_with_variant_from_different_stocks):
order = order_with_variant_from_different_stocks
- lines = order.get_lines().filter(product_sku='SKU_A')
+ lines = order.lines.filter(product_sku='SKU_A')
variant_lines_before = lines.count()
line = lines.get(stock_location='Warehouse 2')
variant = ProductVariant.objects.get(sku='SKU_A')
- quantity_left = add_variant_to_existing_lines(
- line.delivery_group, variant, 2)
+ quantity_left = add_variant_to_existing_lines(line.order, variant, 2)
- lines_after = order.get_lines().filter(product_sku='SKU_A').count()
+ lines_after = order.lines.filter(product_sku='SKU_A').count()
line.refresh_from_db()
assert quantity_left == 0
assert lines_after == variant_lines_before
@@ -517,16 +403,15 @@ def test_add_variant_to_existing_lines_one_line(
def test_add_variant_to_existing_lines_multiple_lines(
order_with_variant_from_different_stocks):
order = order_with_variant_from_different_stocks
- lines = order.get_lines().filter(product_sku='SKU_A')
+ lines = order.lines.filter(product_sku='SKU_A')
variant_lines_before = lines.count()
line_1 = lines.get(stock_location='Warehouse 1')
line_2 = lines.get(stock_location='Warehouse 2')
variant = ProductVariant.objects.get(sku='SKU_A')
- quantity_left = add_variant_to_existing_lines(
- line_1.delivery_group, variant, 4)
+ quantity_left = add_variant_to_existing_lines(line_1.order, variant, 4)
- lines_after = order.get_lines().filter(product_sku='SKU_A').count()
+ lines_after = order.lines.filter(product_sku='SKU_A').count()
line_1.refresh_from_db()
line_2.refresh_from_db()
assert quantity_left == 0
@@ -538,16 +423,15 @@ def test_add_variant_to_existing_lines_multiple_lines(
def test_add_variant_to_existing_lines_multiple_lines_with_rest(
order_with_variant_from_different_stocks):
order = order_with_variant_from_different_stocks
- lines = order.get_lines().filter(product_sku='SKU_A')
+ lines = order.lines.filter(product_sku='SKU_A')
variant_lines_before = lines.count()
line_1 = lines.get(stock_location='Warehouse 1')
line_2 = lines.get(stock_location='Warehouse 2')
variant = ProductVariant.objects.get(sku='SKU_A')
- quantity_left = add_variant_to_existing_lines(
- line_1.delivery_group, variant, 7)
+ quantity_left = add_variant_to_existing_lines(line_1.order, variant, 7)
- lines_after = order.get_lines().filter(product_sku='SKU_A').count()
+ lines_after = order.lines.filter(product_sku='SKU_A').count()
line_1.refresh_from_db()
line_2.refresh_from_db()
assert quantity_left == 2
@@ -556,10 +440,9 @@ def test_add_variant_to_existing_lines_multiple_lines_with_rest(
assert line_2.quantity == 5
-def test_view_add_variant_to_delivery_group(
+def test_view_add_variant_to_order(
admin_client, order_with_variant_from_different_stocks):
order = order_with_variant_from_different_stocks
- group = order.groups.get()
variant = ProductVariant.objects.get(sku='SKU_A')
line = OrderLine.objects.get(
product_sku='SKU_A', stock_location='Warehouse 2')
@@ -576,139 +459,6 @@ def test_view_add_variant_to_delivery_group(
assert line.quantity == 4
-def test_ship_new_delivery_group(delivery_group):
- line = delivery_group.lines.first()
- quantity = line.quantity
- stock = line.stock
- stock_quantity = stock.quantity
- stock_quantity_allocated = stock.quantity_allocated
-
- delivery_group.ship()
- delivery_group.save()
-
- stock.refresh_from_db()
- assert delivery_group.status == GroupStatus.SHIPPED
- assert stock.quantity == stock_quantity - quantity
- assert stock.quantity_allocated == stock_quantity_allocated - quantity
-
-
-def test_cant_ship_cancelled_delivery_group(delivery_group):
- delivery_group.cancel()
- delivery_group.save()
-
- with pytest.raises(TransitionNotAllowed):
- delivery_group.ship()
-
-
-def test_cant_ship_shipped_delivery_group(delivery_group):
- delivery_group.ship()
- delivery_group.save()
-
- with pytest.raises(TransitionNotAllowed):
- delivery_group.ship()
-
-
-def test_cancel_new_delivery_group(delivery_group):
- line = delivery_group.lines.first()
- quantity = line.quantity
- stock = line.stock
- stock_quantity = stock.quantity
- stock_quantity_allocated = stock.quantity_allocated
-
- delivery_group.cancel()
- delivery_group.save()
-
- stock.refresh_from_db()
- assert delivery_group.status == GroupStatus.CANCELLED
- assert stock.quantity == stock_quantity
- assert stock.quantity_allocated == stock_quantity_allocated - quantity
-
-
-def test_cancel_shipped_delivery_group(delivery_group):
- delivery_group.ship()
- delivery_group.save()
-
- line = delivery_group.lines.first()
- quantity = line.quantity
- stock = line.stock
- stock_quantity = stock.quantity
- stock_quantity_allocated = stock.quantity_allocated
-
- delivery_group.cancel()
- delivery_group.save()
-
- stock.refresh_from_db()
- assert delivery_group.status == GroupStatus.CANCELLED
- assert line.stock.quantity == stock_quantity + quantity
- assert line.stock.quantity_allocated == stock_quantity_allocated
-
-
-def test_cant_cancel_cancelled_delivery_group(delivery_group):
- delivery_group.cancel()
- delivery_group.save()
-
- with pytest.raises(TransitionNotAllowed):
- delivery_group.cancel()
-
-
-def test_process_new_delivery_group(billing_address, product_in_stock):
- variant = product_in_stock.variants.get()
- cart = Cart()
- cart.save()
- cart.add(variant, quantity=2)
- order = Order.objects.create(billing_address=billing_address)
- group = DeliveryGroup.objects.create(order=order)
-
- group.process(cart.lines.all())
- group.save()
-
- assert group.status == GroupStatus.NEW
- order_line = group.lines.get()
- stock = order_line.stock
- assert stock.quantity_allocated == 2
-
-
-def test_process_new_delivery_group_with_discount(
- sale, order, request_cart_with_item):
- cart = request_cart_with_item
- group = DeliveryGroup.objects.create(order=order)
-
- group.process(cart.lines.all(), cart.discounts)
- group.save()
-
- line = group.lines.first()
- assert line.unit_price == TaxedMoney(
- net=Money('5', 'USD'), gross=Money('5', 'USD'))
-
-
-def test_cant_process_cancelled_delivery_group(
- delivery_group, product_in_stock):
- delivery_group.cancel()
- delivery_group.save()
-
- variant = product_in_stock.variants.get()
- cart = Cart()
- cart.save()
- cart.add(variant, quantity=2)
-
- with pytest.raises(TransitionNotAllowed):
- delivery_group.process(cart.lines.all())
-
-
-def test_cant_process_shipped_delivery_group(
- delivery_group, product_in_stock):
- delivery_group.ship()
- delivery_group.save()
-
- variant = product_in_stock.variants.get()
- cart = Cart()
- cart.save()
- cart.add(variant, quantity=2)
-
- with pytest.raises(TransitionNotAllowed):
- delivery_group.process(cart.lines.all())
-
-
@patch('saleor.dashboard.order.forms.send_note_confirmation')
def test_note_form_sent_email(
mock_send_note_confirmation, order_with_lines_and_stock):
diff --git a/tests/test_order.py b/tests/test_order.py
index 2370d44610..e74993c833 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -1,5 +1,4 @@
-from decimal import Decimal
-from unittest.mock import Mock, patch
+from unittest.mock import Mock
from django.urls import reverse
from prices import Money, TaxedMoney
@@ -8,7 +7,7 @@ from tests.utils import get_redirect_location
from saleor.order import OrderStatus, models
from saleor.order.emails import collect_data_for_email
from saleor.order.forms import OrderNoteForm
-from saleor.order.utils import add_variant_to_delivery_group, recalculate_order
+from saleor.order.utils import recalculate_order
def test_total_setter():
@@ -33,60 +32,58 @@ def test_order_get_subtotal(order_with_lines):
assert order_with_lines.get_subtotal() == target_subtotal
-def test_add_variant_to_delivery_group_adds_line_for_new_variant(
+def test_add_variant_to_order_adds_line_for_new_variant(
order_with_lines, product_in_stock):
- group = order_with_lines.groups.get()
+ order = order_with_lines
variant = product_in_stock.variants.get()
- lines_before = group.lines.count()
+ lines_before = order.lines.count()
- add_variant_to_delivery_group(group, variant, 1)
+ add_variant_to_order(order, variant, 1)
- line = group.lines.last()
- assert group.lines.count() == lines_before + 1
+ line = order.lines.last()
+ assert order.lines.count() == lines_before + 1
assert line.product_sku == variant.sku
assert line.quantity == 1
-def test_add_variant_to_delivery_group_allocates_stock_for_new_variant(
+def test_add_variant_to_order_allocates_stock_for_new_variant(
order_with_lines, product_in_stock):
- group = order_with_lines.groups.get()
+ order = order_with_lines
variant = product_in_stock.variants.get()
stock = variant.select_stockrecord()
stock_before = stock.quantity_allocated
- add_variant_to_delivery_group(group, variant, 1)
+ add_variant_to_order(order, variant, 1)
stock.refresh_from_db()
assert stock.quantity_allocated == stock_before + 1
-def test_add_variant_to_delivery_group_edits_line_for_existing_variant(
+def test_add_variant_to_order_edits_line_for_existing_variant(
order_with_lines_and_stock):
order = order_with_lines_and_stock
- group = order.groups.get()
- existing_line = group.lines.first()
+ existing_line = order.lines.first()
variant = existing_line.product.variants.get()
- lines_before = group.lines.count()
+ lines_before = order.lines.count()
line_quantity_before = existing_line.quantity
- add_variant_to_delivery_group(group, variant, 1)
+ add_variant_to_order(order, variant, 1)
existing_line.refresh_from_db()
- assert group.lines.count() == lines_before
+ assert order.lines.count() == lines_before
assert existing_line.product_sku == variant.sku
assert existing_line.quantity == line_quantity_before + 1
-def test_add_variant_to_delivery_group_allocates_stock_for_existing_variant(
+def test_add_variant_to_order_allocates_stock_for_existing_variant(
order_with_lines_and_stock):
order = order_with_lines_and_stock
- group = order.groups.get()
- existing_line = group.lines.first()
+ existing_line = order.lines.first()
variant = existing_line.product.variants.get()
stock = existing_line.stock
stock_before = stock.quantity_allocated
- add_variant_to_delivery_group(group, variant, 1)
+ add_variant_to_order(order, variant, 1)
stock.refresh_from_db()
assert stock.quantity_allocated == stock_before + 1
@@ -157,33 +154,6 @@ def test_create_order_history(order_with_lines):
assert history_entry.content == 'test_entry'
-def test_delivery_group_is_shipping_required(delivery_group):
- assert delivery_group.is_shipping_required()
-
-
-def test_delivery_group_is_shipping_required_no_shipping(delivery_group):
- line = delivery_group.lines.first()
- line.is_shipping_required = False
- line.save()
- assert not delivery_group.is_shipping_required()
-
-
-def test_delivery_group_is_shipping_required_partially_required(
- delivery_group, product_without_shipping):
- variant = product_without_shipping.variants.get()
- product_type = product_without_shipping.product_type
- delivery_group.lines.create(
- delivery_group=delivery_group,
- product=product_without_shipping,
- product_name=product_without_shipping.name,
- product_sku=variant.sku,
- is_shipping_required=product_type.is_shipping_required,
- quantity=3,
- unit_price_net=Decimal('30.00'),
- unit_price_gross=Decimal('30.00'))
- assert delivery_group.is_shipping_required()
-
-
def test_collect_data_for_email(order):
template = Mock(spec=str)
order.user_mail = '[email protected]'
diff --git a/tests/test_payment.py b/tests/test_payment.py
index c8c94a896c..6058b6e501 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -9,11 +9,10 @@ def test_get_purchased_items(order_with_lines, settings, voucher):
payment = Payment.objects.create(order=order_with_lines, variant='paypal')
discount = Money('10.0', settings.DEFAULT_CURRENCY)
- assert len(payment.get_purchased_items()) == len(
- order_with_lines.get_lines())
+ assert len(payment.get_purchased_items()) == order_with_lines.lines.count()
for p, o in zip(
- payment.get_purchased_items(), order_with_lines.get_lines()):
+ payment.get_purchased_items(), order_with_lines.lines.all()):
assert p.sku == o.product_sku
assert p.quantity == o.quantity
assert p.price == o.unit_price_gross.quantize(Decimal('0.01')).amount
@@ -26,11 +25,11 @@ def test_get_purchased_items(order_with_lines, settings, voucher):
settings.PAYMENT_VARIANTS = {'paypal': ('PaypalProvider', {})}
- assert len(payment.get_purchased_items()) == len(
- order_with_lines.get_lines()) + 1
+ assert len(payment.get_purchased_items()) == (
+ order_with_lines.lines.count() + 1)
for p, o in zip(
- payment.get_purchased_items()[:-1], order_with_lines.get_lines()):
+ payment.get_purchased_items()[:-1], order_with_lines.lines.all()):
assert p.sku == o.product_sku
assert p.quantity == o.quantity
assert p.price == o.unit_price_gross.quantize(Decimal('0.01')).amount