repo
stringclasses 1
value | pull_number
int64 3.02k
4.02k
| instance_id
stringlengths 31
31
| issue_numbers
sequencelengths 1
2
| base_commit
stringlengths 40
40
| patch
stringlengths 507
53.9k
| test_patch
stringlengths 425
36.1k
| problem_statement
stringlengths 272
5.29k
| hints_text
stringlengths 0
2.33k
| created_at
unknown | version
stringclasses 5
values | ERROR_TO_ERROR
sequencelengths 0
0
| FAIL_TO_PASS
sequencelengths 1
179
| PASS_TO_PASS
sequencelengths 0
90
| environment_setup_commit
stringclasses 5
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
django-oscar/django-oscar | 3,343 | django-oscar__django-oscar-3343 | [
"3344"
] | 2429ad9e88e9a432dfa60aaca703d99860f85389 | diff --git a/src/oscar/apps/offer/benefits.py b/src/oscar/apps/offer/benefits.py
--- a/src/oscar/apps/offer/benefits.py
+++ b/src/oscar/apps/offer/benefits.py
@@ -275,12 +275,15 @@ def apply(self, basket, condition, offer, **kwargs):
# Cheapest line gives free product
discount, line = line_tuples[0]
- apply_discount(line, discount, 1, offer)
+ if line.quantity_with_offer_discount(offer) == 0:
+ apply_discount(line, discount, 1, offer)
- affected_lines = [(line, discount, 1)]
- condition.consume_items(offer, basket, affected_lines)
+ affected_lines = [(line, discount, 1)]
+ condition.consume_items(offer, basket, affected_lines)
- return BasketDiscount(discount)
+ return BasketDiscount(discount)
+ else:
+ return ZERO_DISCOUNT
# =================
| diff --git a/tests/integration/offer/test_applicator.py b/tests/integration/offer/test_applicator.py
--- a/tests/integration/offer/test_applicator.py
+++ b/tests/integration/offer/test_applicator.py
@@ -29,7 +29,6 @@ def test_applies_offer_multiple_times_by_default(self):
add_product(self.basket, D('100'), 5)
offer = ConditionalOfferFactory(
pk=1, condition=self.condition, benefit=self.benefit)
- self.applicator.apply
self.applicator.apply_offers(self.basket, [offer])
line = self.basket.all_lines()[0]
self.assertTrue(line.quantity_with_offer_discount(offer) == 5)
diff --git a/tests/integration/offer/test_multibuy_benefit.py b/tests/integration/offer/test_multibuy_benefit.py
--- a/tests/integration/offer/test_multibuy_benefit.py
+++ b/tests/integration/offer/test_multibuy_benefit.py
@@ -5,8 +5,11 @@
from django.test import TestCase
from oscar.apps.offer import models
-from oscar.test import factories
+from oscar.apps.offer.utils import Applicator
from oscar.test.basket import add_product, add_products
+from oscar.test.factories import (
+ BenefitFactory, ConditionalOfferFactory, ConditionFactory,
+ RangeFactory, create_basket)
class TestAMultibuyDiscountAppliedWithCountCondition(TestCase):
@@ -22,7 +25,7 @@ def setUp(self):
range=range,
type=models.Benefit.MULTIBUY)
self.offer = mock.Mock()
- self.basket = factories.create_basket(empty=True)
+ self.basket = create_basket(empty=True)
def test_applies_correctly_to_empty_basket(self):
result = self.benefit.apply(self.basket, self.condition, self.offer)
@@ -45,6 +48,22 @@ def test_applies_correctly_to_basket_which_exceeds_condition(self):
self.assertEqual(3, self.basket.num_items_with_discount)
self.assertEqual(5, self.basket.num_items_without_discount)
+ def test_apply_offer_with_multibuy_benefit_and_count_condition(self):
+ rng = RangeFactory(includes_all_products=True)
+ condition = ConditionFactory(range=rng, type=ConditionFactory._meta.model.COUNT, value=1)
+ benefit = BenefitFactory(range=rng, type=BenefitFactory._meta.model.MULTIBUY, value=1)
+ offer = ConditionalOfferFactory(condition=condition, benefit=benefit)
+
+ add_product(self.basket, D('100'), 5)
+
+ applicator = Applicator()
+ applicator.apply_offers(self.basket, [offer])
+ line = self.basket.all_lines()[0]
+ assert line.quantity_with_offer_discount(offer) == 1
+
+ self.basket.refresh_from_db()
+ assert self.basket.total_discount == D('100')
+
class TestAMultibuyDiscountAppliedWithAValueCondition(TestCase):
@@ -60,7 +79,7 @@ def setUp(self):
type=models.Benefit.MULTIBUY,
value=1)
self.offer = mock.Mock()
- self.basket = factories.create_basket(empty=True)
+ self.basket = create_basket(empty=True)
def test_applies_correctly_to_empty_basket(self):
result = self.benefit.apply(self.basket, self.condition, self.offer)
@@ -93,7 +112,7 @@ def setUp(self):
type=models.Condition.COUNT,
value=3)
self.offer = mock.Mock()
- self.basket = factories.create_basket(empty=True)
+ self.basket = create_basket(empty=True)
def test_multibuy_range_required(self):
benefit = models.Benefit(
| Issue with `apply` method of `MultibuyDiscountBenefit`
### Issue Summary
`apply` method of `MultibuyDiscountBenefit` does not work as it should. With `Count` condition it makes all items in the basket FOC.
### Steps to Reproduce
Failed test in PR https://github.com/django-oscar/django-oscar/pull/3342
### Technical details
If in the test above we will have more than two items in the basket. E.g.
```python
add_product(self.basket, D('20'), 2)
add_product(self.basket, D('100'), 5)
```
this loop will make 10_000 iterations:
https://github.com/django-oscar/django-oscar/blob/2429ad9e88e9a432dfa60aaca703d99860f85389/src/oscar/apps/offer/applicator.py#L33-L40
Suggested change to `apply` method, please review in PR https://github.com/django-oscar/django-oscar/pull/3343
| "2020-04-09T12:58:41Z" | 2.0 | [] | [
"tests/integration/offer/test_multibuy_benefit.py::TestAMultibuyDiscountAppliedWithCountCondition::test_apply_offer_with_multibuy_benefit_and_count_condition"
] | [
"tests/integration/offer/test_applicator.py::TestOfferApplicator::test_applies_offer_multiple_times_by_default",
"tests/integration/offer/test_applicator.py::TestOfferApplicator::test_get_site_offers",
"tests/integration/offer/test_applicator.py::TestOfferApplicator::test_respects_maximum_applications_field",
"tests/integration/offer/test_applicator.py::TestOfferApplicator::test_uses_offers_in_order_of_descending_priority",
"tests/integration/offer/test_applicator.py::TestOfferApplicationsWrapper::test_aggregates_results_from_same_offer",
"tests/integration/offer/test_applicator.py::TestOfferApplicationsWrapper::test_is_iterable",
"tests/integration/offer/test_multibuy_benefit.py::TestAMultibuyDiscountAppliedWithCountCondition::test_applies_correctly_to_basket_which_exceeds_condition",
"tests/integration/offer/test_multibuy_benefit.py::TestAMultibuyDiscountAppliedWithCountCondition::test_applies_correctly_to_basket_which_matches_condition",
"tests/integration/offer/test_multibuy_benefit.py::TestAMultibuyDiscountAppliedWithCountCondition::test_applies_correctly_to_empty_basket",
"tests/integration/offer/test_multibuy_benefit.py::TestAMultibuyDiscountAppliedWithAValueCondition::test_applies_correctly_to_basket_which_exceeds_condition",
"tests/integration/offer/test_multibuy_benefit.py::TestAMultibuyDiscountAppliedWithAValueCondition::test_applies_correctly_to_basket_which_matches_condition",
"tests/integration/offer/test_multibuy_benefit.py::TestAMultibuyDiscountAppliedWithAValueCondition::test_applies_correctly_to_empty_basket",
"tests/integration/offer/test_multibuy_benefit.py::TestMultibuyValidation::test_multibuy_must_not_have_max_affected_items",
"tests/integration/offer/test_multibuy_benefit.py::TestMultibuyValidation::test_multibuy_must_not_have_value",
"tests/integration/offer/test_multibuy_benefit.py::TestMultibuyValidation::test_multibuy_range_required"
] | 2429ad9e88e9a432dfa60aaca703d99860f85389 |
|
django-oscar/django-oscar | 3,632 | django-oscar__django-oscar-3632 | [
"3614",
"3619"
] | d98bbaccd551bb0accf78adddcc0a661396c1213 | diff --git a/src/oscar/apps/dashboard/offers/apps.py b/src/oscar/apps/dashboard/offers/apps.py
--- a/src/oscar/apps/dashboard/offers/apps.py
+++ b/src/oscar/apps/dashboard/offers/apps.py
@@ -26,12 +26,12 @@ def get_urls(self):
urls = [
path('', self.list_view.as_view(), name='offer-list'),
# Creation
- path('new/name-and-description/', self.metadata_view.as_view(), name='offer-metadata'),
+ path('new/metadata/', self.metadata_view.as_view(), name='offer-metadata'),
path('new/condition/', self.condition_view.as_view(), name='offer-condition'),
path('new/incentive/', self.benefit_view.as_view(), name='offer-benefit'),
path('new/restrictions/', self.restrictions_view.as_view(), name='offer-restrictions'),
# Update
- path('<int:pk>/name-and-description/', self.metadata_view.as_view(update=True), name='offer-metadata'),
+ path('<int:pk>/metadata/', self.metadata_view.as_view(update=True), name='offer-metadata'),
path('<int:pk>/condition/', self.condition_view.as_view(update=True), name='offer-condition'),
path('<int:pk>/incentive/', self.benefit_view.as_view(update=True), name='offer-benefit'),
path('<int:pk>/restrictions/', self.restrictions_view.as_view(update=True), name='offer-restrictions'),
diff --git a/src/oscar/apps/dashboard/offers/forms.py b/src/oscar/apps/dashboard/offers/forms.py
--- a/src/oscar/apps/dashboard/offers/forms.py
+++ b/src/oscar/apps/dashboard/offers/forms.py
@@ -1,6 +1,6 @@
-import datetime
-
from django import forms
+from django.conf import settings
+from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from oscar.core.loading import get_model
@@ -11,10 +11,26 @@
Benefit = get_model('offer', 'Benefit')
+def get_offer_type_choices():
+ return (("", "---------"),) + tuple(choice for choice in ConditionalOffer.TYPE_CHOICES
+ if choice[0] in [getattr(ConditionalOffer, const_name)
+ for const_name in settings.OSCAR_OFFERS_IMPLEMENTED_TYPES])
+
+
class MetaDataForm(forms.ModelForm):
+
+ offer_type = forms.ChoiceField(label=_("Type"), choices=get_offer_type_choices)
+
class Meta:
model = ConditionalOffer
- fields = ('name', 'description',)
+ fields = ('name', 'description', 'offer_type')
+
+ def clean_offer_type(self):
+ data = self.cleaned_data['offer_type']
+ if (self.instance.pk is not None) and (self.instance.offer_type == ConditionalOffer.VOUCHER) and \
+ ('offer_type' in self.changed_data) and self.instance.vouchers.exists():
+ raise forms.ValidationError(_("This can only be changed if it has no vouchers attached to it"))
+ return data
class RestrictionsForm(forms.ModelForm):
@@ -28,8 +44,7 @@ class RestrictionsForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- today = datetime.date.today()
- self.fields['start_datetime'].initial = today
+ self.fields['start_datetime'].initial = timezone.now()
class Meta:
model = ConditionalOffer
@@ -188,4 +203,16 @@ def save(self, *args, **kwargs):
class OfferSearchForm(forms.Form):
name = forms.CharField(required=False, label=_("Offer name"))
- is_active = forms.BooleanField(required=False, label=_("Is active?"))
+ is_active = forms.NullBooleanField(required=False, label=_("Is active?"), widget=widgets.NullBooleanSelect)
+ offer_type = forms.ChoiceField(required=False, label=_("Offer type"), choices=get_offer_type_choices)
+ has_vouchers = forms.NullBooleanField(required=False, label=_("Has vouchers?"), widget=widgets.NullBooleanSelect)
+ voucher_code = forms.CharField(required=False, label=_("Voucher code"))
+
+ basic_fields = [
+ 'name',
+ 'is_active',
+ ]
+
+ @property
+ def is_voucher_offer_type(self):
+ return self.is_bound and (self.cleaned_data['offer_type'] == ConditionalOffer.VOUCHER)
diff --git a/src/oscar/apps/dashboard/offers/views.py b/src/oscar/apps/dashboard/offers/views.py
--- a/src/oscar/apps/dashboard/offers/views.py
+++ b/src/oscar/apps/dashboard/offers/views.py
@@ -5,7 +5,7 @@
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponseRedirect
-from django.shortcuts import get_object_or_404
+from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
@@ -36,39 +36,53 @@ class OfferListView(ListView):
paginate_by = settings.OSCAR_DASHBOARD_ITEMS_PER_PAGE
def get_queryset(self):
- qs = self.model._default_manager.exclude(
- offer_type=ConditionalOffer.VOUCHER)
- qs = sort_queryset(qs, self.request,
- ['name', 'start_datetime', 'end_datetime',
- 'num_applications', 'total_discount'])
+ self.search_filters = []
+ qs = self.model._default_manager.all()
+ qs = sort_queryset(qs, self.request, ['name', 'offer_type', 'start_datetime', 'end_datetime',
+ 'num_applications', 'total_discount'])
- self.description = _("All offers")
-
- # We track whether the queryset is filtered to determine whether we
- # show the search form 'reset' button.
- self.is_filtered = False
self.form = self.form_class(self.request.GET)
- if not self.form.is_valid():
+ # This form is exactly the same as the other one, apart from having
+ # fields with different IDs, so that they are unique within the page
+ # (non-unique field IDs also break Select2)
+ self.advanced_form = self.form_class(self.request.GET, auto_id='id_advanced_%s')
+ if not all([self.form.is_valid(), self.advanced_form.is_valid()]):
return qs
- data = self.form.cleaned_data
-
- if data['name']:
- qs = qs.filter(name__icontains=data['name'])
- self.description = _("Offers matching '%s'") % data['name']
- self.is_filtered = True
- if data['is_active']:
- self.is_filtered = True
- today = timezone.now()
- qs = qs.filter(start_datetime__lte=today, end_datetime__gte=today)
+ name = self.form.cleaned_data['name']
+ offer_type = self.form.cleaned_data['offer_type']
+ is_active = self.form.cleaned_data['is_active']
+ has_vouchers = self.form.cleaned_data['has_vouchers']
+ voucher_code = self.form.cleaned_data['voucher_code']
+
+ if name:
+ qs = qs.filter(name__icontains=name)
+ self.search_filters.append(_('Name matches "%s"') % name)
+ if is_active is not None:
+ now = timezone.now()
+ if is_active:
+ qs = qs.filter(start_datetime__lte=now, end_datetime__gte=now)
+ self.search_filters.append(_("Is active"))
+ else:
+ qs = qs.filter(end_datetime__lt=now)
+ self.search_filters.append(_("Is inactive"))
+ if offer_type:
+ qs = qs.filter(offer_type=offer_type)
+ self.search_filters.append(_('Is of type "%s"') % dict(ConditionalOffer.TYPE_CHOICES)[offer_type])
+ if has_vouchers is not None:
+ qs = qs.filter(vouchers__isnull=not has_vouchers).distinct()
+ self.search_filters.append(_("Has vouchers") if has_vouchers else _("Has no vouchers"))
+ if voucher_code:
+ qs = qs.filter(vouchers__code__icontains=voucher_code).distinct()
+ self.search_filters.append(_('Voucher code matches "%s"') % voucher_code)
return qs
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
- ctx['queryset_description'] = self.description
ctx['form'] = self.form
- ctx['is_filtered'] = self.is_filtered
+ ctx['advanced_form'] = self.advanced_form
+ ctx['search_filters'] = self.search_filters
return ctx
@@ -224,10 +238,11 @@ def form_valid(self, form):
return super().form_valid(form)
def save_offer(self, offer):
- # We update the offer with the name/description from step 1
+ # We update the offer with the name/description/offer_type from step 1
session_offer = self._fetch_session_offer()
offer.name = session_offer.name
offer.description = session_offer.description
+ offer.offer_type = session_offer.offer_type
# Save the related models, then save the offer.
# Note than you can save already on the first page of the wizard,
@@ -279,7 +294,7 @@ def get_instance(self):
return self.offer
def get_title(self):
- return _("Name and description")
+ return _("Name, description and type")
class OfferBenefitView(OfferWizardStepView):
@@ -333,6 +348,13 @@ class OfferDeleteView(DeleteView):
template_name = 'oscar/dashboard/offers/offer_delete.html'
context_object_name = 'offer'
+ def dispatch(self, request, *args, **kwargs):
+ offer = self.get_object()
+ if offer.vouchers.exists():
+ messages.warning(request, _("This offer can only be deleted if it has no vouchers attached to it"))
+ return redirect('dashboard:offer-detail', pk=offer.pk)
+ return super().dispatch(request, *args, **kwargs)
+
def get_success_url(self):
messages.success(self.request, _("Offer deleted!"))
return reverse('dashboard:offer-list')
diff --git a/src/oscar/apps/dashboard/views.py b/src/oscar/apps/dashboard/views.py
--- a/src/oscar/apps/dashboard/views.py
+++ b/src/oscar/apps/dashboard/views.py
@@ -46,15 +46,6 @@ def get_context_data(self, **kwargs):
ctx.update(self.get_stats())
return ctx
- def get_active_site_offers(self):
- """
- Return active conditional offers of type "site offer". The returned
- ``Queryset`` of site offers is filtered by end date greater then
- the current date.
- """
- return ConditionalOffer.objects.filter(
- end_datetime__gt=now(), offer_type=ConditionalOffer.SITE)
-
def get_active_vouchers(self):
"""
Get all active vouchers. The returned ``Queryset`` of vouchers
@@ -188,7 +179,10 @@ def get_stats(self):
}
if user.is_staff:
stats.update(
- total_site_offers=self.get_active_site_offers().count(),
+ offer_maps=(ConditionalOffer.objects.filter(end_datetime__gt=now())
+ .values('offer_type')
+ .annotate(count=Count('id'))
+ .order_by('offer_type')),
total_vouchers=self.get_active_vouchers().count(),
)
return stats
diff --git a/src/oscar/apps/dashboard/vouchers/apps.py b/src/oscar/apps/dashboard/vouchers/apps.py
--- a/src/oscar/apps/dashboard/vouchers/apps.py
+++ b/src/oscar/apps/dashboard/vouchers/apps.py
@@ -29,6 +29,8 @@ def ready(self):
'dashboard.vouchers.views', 'VoucherSetDetailView')
self.set_download_view = get_class(
'dashboard.vouchers.views', 'VoucherSetDownloadView')
+ self.set_delete_view = get_class(
+ 'dashboard.vouchers.views', 'VoucherSetDeleteView')
def get_urls(self):
urls = [
@@ -41,7 +43,8 @@ def get_urls(self):
path('sets/', self.set_list_view.as_view(), name='voucher-set-list'),
path('sets/create/', self.set_create_view.as_view(), name='voucher-set-create'),
path('sets/update/<int:pk>/', self.set_update_view.as_view(), name='voucher-set-update'),
- path('sets/<int:pk>/', self.set_detail_view.as_view(), name='voucher-set'),
- path('sets/<int:pk>/download/', self.set_download_view.as_view(), name='voucher-set-download'),
+ path('sets/detail/<int:pk>/', self.set_detail_view.as_view(), name='voucher-set-detail'),
+ path('sets/download/<int:pk>/', self.set_download_view.as_view(), name='voucher-set-download'),
+ path('sets/delete/<int:pk>/', self.set_delete_view.as_view(), name='voucher-set-delete'),
]
return self.post_process_urls(urls)
diff --git a/src/oscar/apps/dashboard/vouchers/forms.py b/src/oscar/apps/dashboard/vouchers/forms.py
--- a/src/oscar/apps/dashboard/vouchers/forms.py
+++ b/src/oscar/apps/dashboard/vouchers/forms.py
@@ -1,99 +1,73 @@
from django import forms
+from django.db import transaction
+from django.urls import reverse
+from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
+from oscar.apps.voucher.utils import get_unused_code
from oscar.core.loading import get_model
from oscar.forms import widgets
Voucher = get_model('voucher', 'Voucher')
VoucherSet = get_model('voucher', 'VoucherSet')
-Benefit = get_model('offer', 'Benefit')
-Range = get_model('offer', 'Range')
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
-class VoucherForm(forms.Form):
+class VoucherForm(forms.ModelForm):
"""
- A specialised form for creating a voucher and offer
- model.
+ A specialised form for creating a voucher model, and capturing the offers
+ that apply to it.
"""
- name = forms.CharField(label=_("Name"))
- code = forms.CharField(label=_("Code"))
-
- start_datetime = forms.DateTimeField(
- widget=widgets.DateTimePickerInput(),
- label=_("Start datetime"))
- end_datetime = forms.DateTimeField(
- widget=widgets.DateTimePickerInput(),
- label=_("End datetime"))
-
- usage = forms.ChoiceField(choices=Voucher.USAGE_CHOICES, label=_("Usage"))
-
- benefit_range = forms.ModelChoiceField(
- label=_('Which products get a discount?'),
- queryset=Range.objects.all(),
+ offers = forms.ModelMultipleChoiceField(
+ label=_("Which offers apply for this voucher?"),
+ queryset=ConditionalOffer.objects.filter(offer_type=ConditionalOffer.VOUCHER),
)
- benefit_type = forms.ChoiceField(
- choices=Benefit.TYPE_CHOICES,
- label=_('Discount type'),
- )
- benefit_value = forms.DecimalField(
- label=_('Discount value'))
-
- exclusive = forms.BooleanField(
- required=False,
- label=_("Exclusive offers cannot be combined on the same items"))
-
- def __init__(self, voucher=None, *args, **kwargs):
- self.voucher = voucher
- super().__init__(*args, **kwargs)
-
- def clean_name(self):
- name = self.cleaned_data['name']
- try:
- voucher = Voucher.objects.get(name=name)
- except Voucher.DoesNotExist:
- pass
- else:
- if (not self.voucher) or (voucher.id != self.voucher.id):
- raise forms.ValidationError(_("The name '%s' is already in"
- " use") % name)
- return name
+
+ class Meta:
+ model = Voucher
+ fields = [
+ 'name',
+ 'code',
+ 'start_datetime',
+ 'end_datetime',
+ 'usage',
+ ]
+ widgets = {
+ 'start_datetime': widgets.DateTimePickerInput(),
+ 'end_datetime': widgets.DateTimePickerInput(),
+ }
def clean_code(self):
- code = self.cleaned_data['code'].strip().upper()
- if not code:
- raise forms.ValidationError(_("Please enter a voucher code"))
- try:
- voucher = Voucher.objects.get(code=code)
- except Voucher.DoesNotExist:
- pass
- else:
- if (not self.voucher) or (voucher.id != self.voucher.id):
- raise forms.ValidationError(_("The code '%s' is already in"
- " use") % code)
- return code
-
- def clean(self):
- cleaned_data = super().clean()
- start_datetime = cleaned_data.get('start_datetime')
- end_datetime = cleaned_data.get('end_datetime')
- if start_datetime and end_datetime and end_datetime < start_datetime:
- raise forms.ValidationError(_("The start date must be before the"
- " end date"))
- return cleaned_data
+ return self.cleaned_data['code'].strip().upper()
class VoucherSearchForm(forms.Form):
name = forms.CharField(required=False, label=_("Name"))
code = forms.CharField(required=False, label=_("Code"))
- is_active = forms.BooleanField(required=False, label=_("Is Active?"))
- in_set = forms.BooleanField(
- required=False, label=_("In Voucherset?"))
+ offer_name = forms.CharField(required=False, label=_("Offer name"))
+ is_active = forms.NullBooleanField(required=False, label=_("Is active?"), widget=widgets.NullBooleanSelect)
+ in_set = forms.NullBooleanField(required=False, label=_("In voucher set?"), widget=widgets.NullBooleanSelect)
+ has_offers = forms.NullBooleanField(required=False, label=_("Has offers?"), widget=widgets.NullBooleanSelect)
+
+ basic_fields = [
+ 'name',
+ 'code',
+ 'is_active',
+ 'in_set',
+ ]
def clean_code(self):
return self.cleaned_data['code'].upper()
class VoucherSetForm(forms.ModelForm):
+ usage = forms.ChoiceField(choices=(("", "---------"),) + Voucher.USAGE_CHOICES, label=_("Usage"))
+
+ offers = forms.ModelMultipleChoiceField(
+ label=_("Which offers apply for this voucher set?"),
+ queryset=ConditionalOffer.objects.filter(offer_type=ConditionalOffer.VOUCHER),
+ )
+
class Meta:
model = VoucherSet
fields = [
@@ -109,27 +83,48 @@ class Meta:
'end_datetime': widgets.DateTimePickerInput(),
}
- benefit_range = forms.ModelChoiceField(
- label=_('Which products get a discount?'),
- queryset=Range.objects.all(),
- )
- benefit_type = forms.ChoiceField(
- choices=Benefit.TYPE_CHOICES,
- label=_('Discount type'),
- )
- benefit_value = forms.DecimalField(
- label=_('Discount value'))
+ def clean_count(self):
+ data = self.cleaned_data['count']
+ if (self.instance.pk is not None) and (data < self.instance.count):
+ detail_url = reverse('dashboard:voucher-set-detail', kwargs={'pk': self.instance.pk})
+ raise forms.ValidationError(mark_safe(
+ _('This cannot be used to delete vouchers (currently %s) in this set. '
+ 'You can do that on the <a href="%s">detail</a> page.') % (self.instance.count, detail_url)))
+ return data
+ @transaction.atomic
def save(self, commit=True):
instance = super().save(commit)
if commit:
- instance.generate_vouchers()
+ usage = self.cleaned_data['usage']
+ offers = self.cleaned_data['offers']
+ if instance is not None:
+ # Update vouchers in this set
+ for i, voucher in enumerate(instance.vouchers.order_by('date_created')):
+ voucher.name = "%s - %d" % (instance.name, i + 1)
+ voucher.usage = usage
+ voucher.start_datetime = instance.start_datetime
+ voucher.end_datetime = instance.end_datetime
+ voucher.save()
+ voucher.offers.set(offers)
+ # Add vouchers to this set
+ vouchers_added = False
+ for i in range(instance.vouchers.count(), instance.count):
+ voucher = Voucher.objects.create(name="%s - %d" % (instance.name, i + 1),
+ code=get_unused_code(length=instance.code_length),
+ voucher_set=instance,
+ usage=usage,
+ start_datetime=instance.start_datetime,
+ end_datetime=instance.end_datetime)
+ voucher.offers.add(*offers)
+ vouchers_added = True
+ if vouchers_added:
+ instance.update_count()
return instance
class VoucherSetSearchForm(forms.Form):
code = forms.CharField(required=False, label=_("Code"))
- is_active = forms.BooleanField(required=False, label=_("Is Active?"))
def clean_code(self):
return self.cleaned_data['code'].upper()
diff --git a/src/oscar/apps/dashboard/vouchers/views.py b/src/oscar/apps/dashboard/vouchers/views.py
--- a/src/oscar/apps/dashboard/vouchers/views.py
+++ b/src/oscar/apps/dashboard/vouchers/views.py
@@ -3,14 +3,13 @@
from django.conf import settings
from django.contrib import messages
from django.db import transaction
-from django.http import HttpResponse, HttpResponseRedirect
-from django.shortcuts import get_object_or_404
-from django.urls import reverse
+from django.http import HttpResponse
+from django.shortcuts import get_object_or_404, redirect
+from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.views import generic
-from oscar.apps.voucher.utils import get_offer_name
from oscar.core.loading import get_class, get_model
from oscar.core.utils import slugify
from oscar.views import sort_queryset
@@ -21,9 +20,6 @@
VoucherSearchForm = get_class('dashboard.vouchers.forms', 'VoucherSearchForm')
Voucher = get_model('voucher', 'Voucher')
VoucherSet = get_model('voucher', 'VoucherSet')
-ConditionalOffer = get_model('offer', 'ConditionalOffer')
-Benefit = get_model('offer', 'Benefit')
-Condition = get_model('offer', 'Condition')
OrderDiscount = get_model('order', 'OrderDiscount')
@@ -32,62 +28,80 @@ class VoucherListView(generic.ListView):
context_object_name = 'vouchers'
template_name = 'oscar/dashboard/vouchers/voucher_list.html'
form_class = VoucherSearchForm
- description_template = _("%(main_filter)s %(name_filter)s %(code_filter)s")
paginate_by = settings.OSCAR_DASHBOARD_ITEMS_PER_PAGE
def get_queryset(self):
- qs = self.model.objects.all().order_by('-date_created')
+ self.search_filters = []
+ qs = self.model._default_manager.all()
qs = sort_queryset(qs, self.request,
['num_basket_additions', 'num_orders',
'date_created'],
'-date_created')
- self.description_ctx = {'main_filter': _('All vouchers'),
- 'name_filter': '',
- 'code_filter': ''}
- # If form not submitted, return early
- is_form_submitted = 'name' in self.request.GET
- if not is_form_submitted:
- self.form = self.form_class()
+ # If form is not submitted, perform a default filter, and return early
+ if not self.request.GET:
+ self.form = self.form_class(initial={'in_set': False})
+ # This form is exactly the same as the other one, apart from having
+ # fields with different IDs, so that they are unique within the page
+ # (non-unique field IDs also break Select2)
+ self.advanced_form = self.form_class(initial={'in_set': False}, auto_id='id_advanced_%s')
+ self.search_filters.append(_("Not in a set"))
return qs.filter(voucher_set__isnull=True)
self.form = self.form_class(self.request.GET)
- if not self.form.is_valid():
+ # This form is exactly the same as the other one, apart from having
+ # fields with different IDs, so that they are unique within the page
+ # (non-unique field IDs also break Select2)
+ self.advanced_form = self.form_class(self.request.GET, auto_id='id_advanced_%s')
+ if not all([self.form.is_valid(), self.advanced_form.is_valid()]):
return qs
- data = self.form.cleaned_data
- if data['name']:
- qs = qs.filter(name__icontains=data['name'])
- self.description_ctx['name_filter'] \
- = _("with name matching '%s'") % data['name']
- if data['code']:
- qs = qs.filter(code=data['code'])
- self.description_ctx['code_filter'] \
- = _("with code '%s'") % data['code']
- if data['is_active']:
+ name = self.form.cleaned_data['name']
+ code = self.form.cleaned_data['code']
+ offer_name = self.form.cleaned_data['offer_name']
+ is_active = self.form.cleaned_data['is_active']
+ in_set = self.form.cleaned_data['in_set']
+ has_offers = self.form.cleaned_data['has_offers']
+
+ if name:
+ qs = qs.filter(name__icontains=name)
+ self.search_filters.append(_('Name matches "%s"') % name)
+ if code:
+ qs = qs.filter(code=code)
+ self.search_filters.append(_('Code is "%s"') % code)
+ if offer_name:
+ qs = qs.filter(offers__name__icontains=offer_name)
+ self.search_filters.append(_('Offer name matches "%s"') % offer_name)
+ if is_active is not None:
now = timezone.now()
- qs = qs.filter(start_datetime__lte=now, end_datetime__gte=now)
- self.description_ctx['main_filter'] = _('Active vouchers')
- if not data['in_set']:
- qs = qs.filter(voucher_set__isnull=True)
+ if is_active:
+ qs = qs.filter(start_datetime__lte=now, end_datetime__gte=now)
+ self.search_filters.append(_("Is active"))
+ else:
+ qs = qs.filter(end_datetime__lt=now)
+ self.search_filters.append(_("Is inactive"))
+ if in_set is not None:
+ qs = qs.filter(voucher_set__isnull=not in_set)
+ self.search_filters.append(_("In a set") if in_set else _("Not in a set"))
+ if has_offers is not None:
+ qs = qs.filter(offers__isnull=not has_offers).distinct()
+ self.search_filters.append(_("Has offers") if has_offers else _("Has no offers"))
return qs
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
- if self.form.is_bound:
- description = self.description_template % self.description_ctx
- else:
- description = _("Vouchers")
- ctx['description'] = description
ctx['form'] = self.form
+ ctx['advanced_form'] = self.advanced_form
+ ctx['search_filters'] = self.search_filters
return ctx
-class VoucherCreateView(generic.FormView):
+class VoucherCreateView(generic.CreateView):
model = Voucher
template_name = 'oscar/dashboard/vouchers/voucher_form.html'
form_class = VoucherForm
+ success_url = reverse_lazy('dashboard:voucher-list')
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
@@ -95,44 +109,19 @@ def get_context_data(self, **kwargs):
return ctx
def get_initial(self):
- return dict(
- exclusive=True
- )
+ initial = super().get_initial()
+ initial['start_datetime'] = timezone.now()
+ return initial
@transaction.atomic()
def form_valid(self, form):
- # Create offer and benefit
- condition = Condition.objects.create(
- range=form.cleaned_data['benefit_range'],
- type=Condition.COUNT,
- value=1
- )
- benefit = Benefit.objects.create(
- range=form.cleaned_data['benefit_range'],
- type=form.cleaned_data['benefit_type'],
- value=form.cleaned_data['benefit_value']
- )
- name = form.cleaned_data['name']
- offer = ConditionalOffer.objects.create(
- name=get_offer_name(name),
- offer_type=ConditionalOffer.VOUCHER,
- benefit=benefit,
- condition=condition,
- exclusive=form.cleaned_data['exclusive'],
- )
- voucher = Voucher.objects.create(
- name=name,
- code=form.cleaned_data['code'],
- usage=form.cleaned_data['usage'],
- start_datetime=form.cleaned_data['start_datetime'],
- end_datetime=form.cleaned_data['end_datetime'],
- )
- voucher.offers.add(offer)
- return HttpResponseRedirect(self.get_success_url())
+ response = super().form_valid(form)
+ self.object.offers.add(*form.cleaned_data['offers'])
+ return response
def get_success_url(self):
messages.success(self.request, _("Voucher created"))
- return reverse('dashboard:voucher-list')
+ return super().get_success_url()
class VoucherStatsView(generic.DetailView):
@@ -148,72 +137,39 @@ def get_context_data(self, **kwargs):
return ctx
-class VoucherUpdateView(generic.FormView):
+class VoucherUpdateView(generic.UpdateView):
template_name = 'oscar/dashboard/vouchers/voucher_form.html'
+ context_object_name = 'voucher'
model = Voucher
form_class = VoucherForm
+ success_url = reverse_lazy('dashboard:voucher-list')
- def get_voucher(self):
- if not hasattr(self, 'voucher'):
- self.voucher = Voucher.objects.get(id=self.kwargs['pk'])
- return self.voucher
+ def dispatch(self, request, *args, **kwargs):
+ voucher_set = self.get_object().voucher_set
+ if voucher_set is not None:
+ messages.warning(request, _("The voucher can only be edited as part of its set"))
+ return redirect('dashboard:voucher-set-update', pk=voucher_set.pk)
+ return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
- ctx['title'] = self.voucher.name
- ctx['voucher'] = self.voucher
+ ctx['title'] = self.object.name
return ctx
- def get_form_kwargs(self):
- kwargs = super().get_form_kwargs()
- kwargs['voucher'] = self.get_voucher()
- return kwargs
-
def get_initial(self):
- voucher = self.get_voucher()
- offer = voucher.offers.first()
- benefit = offer.benefit
- return {
- 'name': voucher.name,
- 'code': voucher.code,
- 'start_datetime': voucher.start_datetime,
- 'end_datetime': voucher.end_datetime,
- 'usage': voucher.usage,
- 'benefit_type': benefit.type,
- 'benefit_range': benefit.range,
- 'benefit_value': benefit.value,
- 'exclusive': offer.exclusive,
- }
+ initial = super().get_initial()
+ initial['offers'] = self.object.offers.all()
+ return initial
@transaction.atomic()
def form_valid(self, form):
- voucher = self.get_voucher()
- voucher.name = form.cleaned_data['name']
- voucher.code = form.cleaned_data['code']
- voucher.usage = form.cleaned_data['usage']
- voucher.start_datetime = form.cleaned_data['start_datetime']
- voucher.end_datetime = form.cleaned_data['end_datetime']
- voucher.save()
-
- offer = voucher.offers.first()
- offer.condition.range = form.cleaned_data['benefit_range']
- offer.condition.save()
-
- offer.exclusive = form.cleaned_data['exclusive']
- offer.name = get_offer_name(voucher.name)
- offer.save()
-
- benefit = voucher.benefit
- benefit.range = form.cleaned_data['benefit_range']
- benefit.type = form.cleaned_data['benefit_type']
- benefit.value = form.cleaned_data['benefit_value']
- benefit.save()
-
- return HttpResponseRedirect(self.get_success_url())
+ response = super().form_valid(form)
+ self.object.offers.set(form.cleaned_data['offers'])
+ return response
def get_success_url(self):
messages.success(self.request, _("Voucher updated"))
- return reverse('dashboard:voucher-list')
+ return super().get_success_url()
class VoucherDeleteView(generic.DeleteView):
@@ -221,9 +177,19 @@ class VoucherDeleteView(generic.DeleteView):
template_name = 'oscar/dashboard/vouchers/voucher_delete.html'
context_object_name = 'voucher'
+ @transaction.atomic
+ def delete(self, request, *args, **kwargs):
+ response = super().delete(request, *args, **kwargs)
+ if self.object.voucher_set is not None:
+ self.object.voucher_set.update_count()
+ return response
+
def get_success_url(self):
messages.warning(self.request, _("Voucher deleted"))
- return reverse('dashboard:voucher-list')
+ if self.object.voucher_set is not None:
+ return reverse('dashboard:voucher-set-detail', kwargs={'pk': self.object.voucher_set.pk})
+ else:
+ return reverse('dashboard:voucher-list')
class VoucherSetCreateView(generic.CreateView):
@@ -237,40 +203,9 @@ def get_context_data(self, **kwargs):
return ctx
def get_initial(self):
- return {
- 'start_datetime': timezone.now(),
- 'end_datetime': timezone.now()
- }
-
- def form_valid(self, form):
- condition = Condition.objects.create(
- range=form.cleaned_data['benefit_range'],
- type=Condition.COUNT,
- value=1
- )
- benefit = Benefit.objects.create(
- range=form.cleaned_data['benefit_range'],
- type=form.cleaned_data['benefit_type'],
- value=form.cleaned_data['benefit_value']
- )
- name = form.cleaned_data['name']
- offer = ConditionalOffer.objects.create(
- name=get_offer_name(name),
- offer_type=ConditionalOffer.VOUCHER,
- benefit=benefit,
- condition=condition,
- )
-
- VoucherSet.objects.create(
- name=name,
- count=form.cleaned_data['count'],
- code_length=form.cleaned_data['code_length'],
- description=form.cleaned_data['description'],
- start_datetime=form.cleaned_data['start_datetime'],
- end_datetime=form.cleaned_data['end_datetime'],
- offer=offer,
- )
- return HttpResponseRedirect(self.get_success_url())
+ initial = super().get_initial()
+ initial['start_datetime'] = timezone.now()
+ return initial
def get_success_url(self):
messages.success(self.request, _("Voucher set created"))
@@ -280,78 +215,27 @@ def get_success_url(self):
class VoucherSetUpdateView(generic.UpdateView):
template_name = 'oscar/dashboard/vouchers/voucher_set_form.html'
model = VoucherSet
+ context_object_name = 'voucher_set'
form_class = VoucherSetForm
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['title'] = self.object.name
- ctx['voucher'] = self.object
return ctx
- def get_voucherset(self):
- if not hasattr(self, 'voucherset'):
- self.voucherset = VoucherSet.objects.get(id=self.kwargs['pk'])
- return self.voucherset
-
def get_initial(self):
- voucherset = self.get_voucherset()
- offer = voucherset.offer
- benefit = offer.benefit
- return {
- 'name': voucherset.name,
- 'count': voucherset.count,
- 'code_length': voucherset.code_length,
- 'start_datetime': voucherset.start_datetime,
- 'end_datetime': voucherset.end_datetime,
- 'description': voucherset.description,
- 'benefit_type': benefit.type,
- 'benefit_range': benefit.range,
- 'benefit_value': benefit.value,
- }
-
- def form_valid(self, form):
- voucherset = form.save()
- if not voucherset.offer:
- condition = Condition.objects.create(
- range=form.cleaned_data['benefit_range'],
- type=Condition.COUNT,
- value=1
- )
- benefit = Benefit.objects.create(
- range=form.cleaned_data['benefit_range'],
- type=form.cleaned_data['benefit_type'],
- value=form.cleaned_data['benefit_value']
- )
- name = form.cleaned_data['name']
- offer, __ = ConditionalOffer.objects.update_or_create(
- name=get_offer_name(name),
- defaults=dict(
- offer_type=ConditionalOffer.VOUCHER,
- benefit=benefit,
- condition=condition,
- )
- )
- voucherset.offer = offer
- for voucher in voucherset.vouchers.all():
- if offer not in voucher.offers.all():
- voucher.offers.add(offer)
-
- else:
- benefit = voucherset.offer.benefit
- benefit.range = form.cleaned_data['benefit_range']
- benefit.type = form.cleaned_data['benefit_type']
- benefit.value = form.cleaned_data['benefit_value']
- benefit.save()
- condition = voucherset.offer.condition
- condition.range = form.cleaned_data['benefit_range']
- condition.save()
- voucherset.save()
-
- return HttpResponseRedirect(self.get_success_url())
+ initial = super().get_initial()
+ # All vouchers in the set have the same "usage" and "offers", so we use
+ # the first one
+ voucher = self.object.vouchers.first()
+ if voucher is not None:
+ initial['usage'] = voucher.usage
+ initial['offers'] = voucher.offers.all()
+ return initial
def get_success_url(self):
messages.success(self.request, _("Voucher updated"))
- return reverse('dashboard:voucher-set', kwargs={'pk': self.object.pk})
+ return reverse('dashboard:voucher-set-detail', kwargs={'pk': self.object.pk})
class VoucherSetDetailView(generic.ListView):
@@ -360,7 +244,6 @@ class VoucherSetDetailView(generic.ListView):
context_object_name = 'vouchers'
template_name = 'oscar/dashboard/vouchers/voucher_set_detail.html'
form_class = VoucherSetSearchForm
- description_template = _("%(main_filter)s %(name_filter)s %(code_filter)s")
paginate_by = 50
def dispatch(self, request, *args, **kwargs):
@@ -368,6 +251,7 @@ def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get_queryset(self):
+ self.search_filters = []
qs = (
self.model.objects
.filter(voucher_set=self.voucher_set)
@@ -377,9 +261,6 @@ def get_queryset(self):
['num_basket_additions', 'num_orders',
'date_created'],
'-date_created')
- self.description_ctx = {'main_filter': _('All vouchers'),
- 'name_filter': '',
- 'code_filter': ''}
# If form not submitted, return early
is_form_submitted = (
@@ -396,28 +277,22 @@ def get_queryset(self):
data = self.form.cleaned_data
if data['code']:
qs = qs.filter(code__icontains=data['code'])
- self.description_ctx['code_filter'] \
- = _("with code '%s'") % data['code']
- if data['is_active']:
- now = timezone.now()
- qs = qs.filter(start_datetime__lte=now, end_datetime__gt=now)
- self.description_ctx['main_filter'] = _('Active vouchers')
+ self.search_filters.append(_('Code matches "%s"') % data['code'])
return qs
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['voucher_set'] = self.voucher_set
- ctx['description'] = self.voucher_set.name
ctx['form'] = self.form
+ ctx['search_filters'] = self.search_filters
return ctx
class VoucherSetListView(generic.ListView):
model = VoucherSet
- context_object_name = 'vouchers'
+ context_object_name = 'voucher_sets'
template_name = 'oscar/dashboard/vouchers/voucher_set_list.html'
- description_template = _("%(main_filter)s %(name_filter)s %(code_filter)s")
paginate_by = settings.OSCAR_DASHBOARD_ITEMS_PER_PAGE
def get_queryset(self):
@@ -451,3 +326,13 @@ def get(self, request, *args, **kwargs):
writer.writerow([code])
return response
+
+
+class VoucherSetDeleteView(generic.DeleteView):
+ model = VoucherSet
+ template_name = 'oscar/dashboard/vouchers/voucher_set_delete.html'
+ context_object_name = 'voucher_set'
+
+ def get_success_url(self):
+ messages.warning(self.request, _("Voucher set deleted"))
+ return reverse('dashboard:voucher-set-list')
diff --git a/src/oscar/apps/offer/abstract_models.py b/src/oscar/apps/offer/abstract_models.py
--- a/src/oscar/apps/offer/abstract_models.py
+++ b/src/oscar/apps/offer/abstract_models.py
@@ -248,6 +248,10 @@ def clean(self):
raise exceptions.ValidationError(
_('End date should be later than start date'))
+ @property
+ def is_voucher_offer_type(self):
+ return self.offer_type == self.VOUCHER
+
@property
def is_open(self):
return self.status == self.OPEN
diff --git a/src/oscar/apps/offer/apps.py b/src/oscar/apps/offer/apps.py
--- a/src/oscar/apps/offer/apps.py
+++ b/src/oscar/apps/offer/apps.py
@@ -13,7 +13,7 @@ class OfferConfig(OscarConfig):
namespace = 'offer'
def ready(self):
- from . import signals # noqa
+ from . import receivers # noqa
self.detail_view = get_class('offer.views', 'OfferDetailView')
self.list_view = get_class('offer.views', 'OfferListView')
diff --git a/src/oscar/apps/offer/signals.py b/src/oscar/apps/offer/receivers.py
similarity index 100%
rename from src/oscar/apps/offer/signals.py
rename to src/oscar/apps/offer/receivers.py
diff --git a/src/oscar/apps/voucher/abstract_models.py b/src/oscar/apps/voucher/abstract_models.py
--- a/src/oscar/apps/voucher/abstract_models.py
+++ b/src/oscar/apps/voucher/abstract_models.py
@@ -1,14 +1,13 @@
from decimal import Decimal
from django.core import exceptions
-from django.db import models, transaction
+from django.db import models
from django.db.models import Sum
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
-from oscar.apps.voucher.utils import get_unused_code
from oscar.core.compat import AUTH_USER_MODEL
-from oscar.core.loading import get_model
+from oscar.core.decorators import deprecated
class AbstractVoucherSet(models.Model):
@@ -17,7 +16,7 @@ class AbstractVoucherSet(models.Model):
a VoucherSet is a group of voucher that are generated
automatically.
- - count: the minimum number of vouchers in the set. If this is kept at
+ - count: the number of vouchers in the set. If this is kept at
zero, vouchers are created when and as needed.
- code_length: the length of the voucher code. Codes are by default created
@@ -28,7 +27,7 @@ class AbstractVoucherSet(models.Model):
range for all vouchers in the set.
"""
- name = models.CharField(verbose_name=_('Name'), max_length=100)
+ name = models.CharField(verbose_name=_('Name'), max_length=100, unique=True)
count = models.PositiveIntegerField(verbose_name=_('Number of vouchers'))
code_length = models.IntegerField(
verbose_name=_('Length of Code'), default=12)
@@ -37,11 +36,6 @@ class AbstractVoucherSet(models.Model):
start_datetime = models.DateTimeField(_('Start datetime'))
end_datetime = models.DateTimeField(_('End datetime'))
- offer = models.OneToOneField(
- 'offer.ConditionalOffer', related_name='voucher_set',
- verbose_name=_("Offer"), limit_choices_to={'offer_type': "Voucher"},
- on_delete=models.CASCADE, null=True, blank=True)
-
class Meta:
abstract = True
app_label = 'voucher'
@@ -53,44 +47,21 @@ class Meta:
def __str__(self):
return self.name
- def generate_vouchers(self):
- """Generate vouchers for this set"""
- current_count = self.vouchers.count()
- for i in range(current_count, self.count):
- self.add_new()
-
- def add_new(self):
- """Add a new voucher to this set"""
- Voucher = get_model('voucher', 'Voucher')
- code = get_unused_code(length=self.code_length)
- voucher = Voucher.objects.create(
- name=self.name,
- code=code,
- voucher_set=self,
- usage=Voucher.SINGLE_USE,
- start_datetime=self.start_datetime,
- end_datetime=self.end_datetime)
-
- if self.offer:
- voucher.offers.add(self.offer)
-
- return voucher
+ def clean(self):
+ if self.start_datetime and self.end_datetime and (self.start_datetime > self.end_datetime):
+ raise exceptions.ValidationError(_('End date should be later than start date'))
+
+ def update_count(self):
+ vouchers_count = self.vouchers.count()
+ if self.count != vouchers_count:
+ self.count = vouchers_count
+ self.save()
def is_active(self, test_datetime=None):
"""Test whether this voucher set is currently active. """
test_datetime = test_datetime or timezone.now()
return self.start_datetime <= test_datetime <= self.end_datetime
- def save(self, *args, **kwargs):
- self.count = max(self.count, self.vouchers.count())
- with transaction.atomic():
- super().save(*args, **kwargs)
- self.generate_vouchers()
- self.vouchers.update(
- start_datetime=self.start_datetime,
- end_datetime=self.end_datetime
- )
-
@property
def num_basket_additions(self):
value = self.vouchers.aggregate(result=Sum('num_basket_additions'))
@@ -119,7 +90,7 @@ class AbstractVoucher(models.Model):
Oscar enforces those modes by creating VoucherApplication
instances when a voucher is used for an order.
"""
- name = models.CharField(_("Name"), max_length=128,
+ name = models.CharField(_("Name"), max_length=128, unique=True,
help_text=_("This will be shown in the checkout"
" and basket once the voucher is"
" entered"))
@@ -170,8 +141,7 @@ def __str__(self):
return self.name
def clean(self):
- if all([self.start_datetime, self.end_datetime,
- self.start_datetime > self.end_datetime]):
+ if self.start_datetime and self.end_datetime and (self.start_datetime > self.end_datetime):
raise exceptions.ValidationError(
_('End date should be later than start date'))
@@ -260,6 +230,7 @@ def record_discount(self, discount):
record_discount.alters_data = True
@property
+ @deprecated
def benefit(self):
"""
Returns the first offer's benefit instance.
diff --git a/src/oscar/apps/voucher/apps.py b/src/oscar/apps/voucher/apps.py
--- a/src/oscar/apps/voucher/apps.py
+++ b/src/oscar/apps/voucher/apps.py
@@ -10,4 +10,3 @@ class VoucherConfig(OscarConfig):
def ready(self):
from . import receivers # noqa
- from . import signals # noqa
diff --git a/src/oscar/apps/voucher/migrations/0009_make_voucher_names_unique.py b/src/oscar/apps/voucher/migrations/0009_make_voucher_names_unique.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/voucher/migrations/0009_make_voucher_names_unique.py
@@ -0,0 +1,33 @@
+# Generated by Django 3.1.2 on 2021-02-24 06:18
+
+from django.db import migrations
+
+
+def make_voucher_names_unique(apps, schema_editor):
+ """
+ Appends a number to non-unique voucher names.
+ """
+ Voucher = apps.get_model('voucher', 'Voucher')
+ vouchers = Voucher.objects.order_by('date_created')
+ # Find vouchers with non-unique names
+ vouchers_for_name = {}
+ for voucher in vouchers:
+ if voucher.name not in vouchers_for_name:
+ vouchers_for_name[voucher.name] = []
+ vouchers_for_name[voucher.name].append(voucher.id)
+ # Change names for vouchers with non-unique names
+ for voucher in vouchers:
+ if len(vouchers_for_name[voucher.name]) > 1:
+ voucher.name = "%s - %d" % (voucher.name, vouchers_for_name[voucher.name].index(voucher.id) + 1)
+ voucher.save()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('voucher', '0008_auto_20200801_0817'),
+ ]
+
+ operations = [
+ migrations.RunPython(make_voucher_names_unique, migrations.RunPython.noop),
+ ]
diff --git a/src/oscar/apps/voucher/migrations/0010_auto_20210224_0712.py b/src/oscar/apps/voucher/migrations/0010_auto_20210224_0712.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/voucher/migrations/0010_auto_20210224_0712.py
@@ -0,0 +1,27 @@
+# Generated by Django 3.1.2 on 2021-02-24 07:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('voucher', '0009_make_voucher_names_unique'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='voucher',
+ name='name',
+ field=models.CharField(help_text='This will be shown in the checkout and basket once the voucher is entered', max_length=128, unique=True, verbose_name='Name'),
+ ),
+ migrations.AlterField(
+ model_name='voucherset',
+ name='name',
+ field=models.CharField(max_length=100, unique=True, verbose_name='Name'),
+ ),
+ migrations.RemoveField(
+ model_name='voucherset',
+ name='offer',
+ ),
+ ]
diff --git a/src/oscar/apps/voucher/signals.py b/src/oscar/apps/voucher/signals.py
deleted file mode 100644
--- a/src/oscar/apps/voucher/signals.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from django.db.models.signals import post_delete
-from django.dispatch import receiver
-
-from oscar.apps.voucher.utils import get_offer_name
-from oscar.core.loading import get_model
-
-Voucher = get_model('voucher', 'Voucher')
-ConditionalOffer = get_model('offer', 'ConditionalOffer')
-
-
-@receiver(post_delete, sender=Voucher)
-def delete_unused_related_conditional_offer(instance, **kwargs):
- voucher = instance # the object is no longer in the database
-
- try:
- conditional_offer = ConditionalOffer.objects.get(
- name=get_offer_name(voucher.name),
- offer_type=ConditionalOffer.VOUCHER
- )
- except (ConditionalOffer.DoesNotExist, ConditionalOffer.MultipleObjectsReturned):
- pass
- else:
- # Only delete if not used by other vouchers
- if not conditional_offer.vouchers.exists():
- conditional_offer.delete()
diff --git a/src/oscar/apps/voucher/utils.py b/src/oscar/apps/voucher/utils.py
--- a/src/oscar/apps/voucher/utils.py
+++ b/src/oscar/apps/voucher/utils.py
@@ -1,7 +1,6 @@
from itertools import zip_longest
from django.utils.crypto import get_random_string
-from django.utils.translation import gettext_lazy as _
from oscar.core.loading import get_model
@@ -34,11 +33,3 @@ def get_unused_code(length=12, group_length=4, separator='-'):
separator=separator)
if not Voucher.objects.filter(code=code).exists():
return code
-
-
-def get_offer_name(voucher_name):
- """
- Return the name used for the auto-generated offer created
- when a voucher is created through the dashboard.
- """
- return _("Offer for voucher '%s'") % voucher_name
diff --git a/src/oscar/defaults.py b/src/oscar/defaults.py
--- a/src/oscar/defaults.py
+++ b/src/oscar/defaults.py
@@ -82,6 +82,12 @@
# Offers
OSCAR_OFFERS_INCL_TAX = False
+# Values (using the names of the model constants) from
+# "offer.ConditionalOffer.TYPE_CHOICES"
+OSCAR_OFFERS_IMPLEMENTED_TYPES = [
+ 'SITE',
+ 'VOUCHER',
+]
# Hidden Oscar features, e.g. wishlists or reviews
OSCAR_HIDDEN_FEATURES = []
diff --git a/src/oscar/forms/widgets.py b/src/oscar/forms/widgets.py
--- a/src/oscar/forms/widgets.py
+++ b/src/oscar/forms/widgets.py
@@ -6,6 +6,7 @@
from django.forms.widgets import FileInput
from django.utils import formats
from django.utils.encoding import force_str
+from django.utils.translation import gettext as _
class ImageInput(FileInput):
@@ -286,3 +287,18 @@ def optgroups(self, name, value, attrs=None):
class MultipleRemoteSelect(RemoteSelect):
allow_multiple_selected = True
+
+
+class NullBooleanSelect(forms.NullBooleanSelect):
+ """
+ Customised NullBooleanSelect widget that gives the "unknown" choice a more
+ meaningful label than the default of "Unknown".
+ """
+
+ def __init__(self, attrs=None):
+ super().__init__(attrs)
+ self.choices = (
+ ('unknown', _('---------')),
+ ('true', _('Yes')),
+ ('false', _('No')),
+ )
| diff --git a/src/oscar/test/factories/offer.py b/src/oscar/test/factories/offer.py
--- a/src/oscar/test/factories/offer.py
+++ b/src/oscar/test/factories/offer.py
@@ -2,6 +2,8 @@
from oscar.core.loading import get_model
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
+
__all__ = [
'RangeFactory', 'ConditionFactory', 'BenefitFactory',
'ConditionalOfferFactory',
@@ -47,6 +49,7 @@ class Meta:
class ConditionalOfferFactory(factory.django.DjangoModelFactory):
name = factory.Sequence(lambda n: 'Test offer %d' % n)
+ offer_type = ConditionalOffer.SITE
benefit = factory.SubFactory(BenefitFactory)
condition = factory.SubFactory(ConditionFactory)
diff --git a/src/oscar/test/factories/voucher.py b/src/oscar/test/factories/voucher.py
--- a/src/oscar/test/factories/voucher.py
+++ b/src/oscar/test/factories/voucher.py
@@ -3,15 +3,20 @@
import factory
from django.utils.timezone import now
+from oscar.apps.voucher.utils import get_unused_code
from oscar.core.loading import get_model
from oscar.test.factories import ConditionalOfferFactory
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
+Voucher = get_model('voucher', 'Voucher')
+
__all__ = ['VoucherFactory', 'VoucherSetFactory']
class VoucherFactory(factory.django.DjangoModelFactory):
name = "My voucher"
code = "MYVOUCHER"
+ usage = Voucher.MULTI_USE
start_datetime = now() - datetime.timedelta(days=1)
end_datetime = now() + datetime.timedelta(days=10)
@@ -24,9 +29,23 @@ class VoucherSetFactory(factory.django.DjangoModelFactory):
name = factory.Sequence(lambda n: 'Voucher Set %d' % n)
count = 100
code_length = 12
+ description = "Dummy description"
start_datetime = now() - datetime.timedelta(days=1)
end_datetime = now() + datetime.timedelta(days=10)
- offer = factory.SubFactory(ConditionalOfferFactory)
class Meta:
model = get_model('voucher', 'VoucherSet')
+
+ @factory.post_generation
+ def vouchers(obj, create, extracted, **kwargs):
+ if not create:
+ return
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)
+ for i in range(0, obj.count):
+ voucher = Voucher.objects.create(name="%s - %d" % (obj.name, i + 1),
+ code=get_unused_code(length=obj.code_length),
+ voucher_set=obj,
+ usage=Voucher.MULTI_USE,
+ start_datetime=obj.start_datetime,
+ end_datetime=obj.end_datetime)
+ voucher.offers.add(offer)
diff --git a/tests/functional/dashboard/test_dashboard.py b/tests/functional/dashboard/test_dashboard.py
--- a/tests/functional/dashboard/test_dashboard.py
+++ b/tests/functional/dashboard/test_dashboard.py
@@ -32,7 +32,7 @@
'order_status_breakdown',
)
STAFF_STATS_KEYS = (
- 'total_site_offers',
+ 'offer_maps',
'total_vouchers',
)
diff --git a/tests/functional/dashboard/test_offer.py b/tests/functional/dashboard/test_offer.py
--- a/tests/functional/dashboard/test_offer.py
+++ b/tests/functional/dashboard/test_offer.py
@@ -20,6 +20,7 @@ def test_can_create_an_offer(self):
metadata_page = list_page.click('Create new offer')
metadata_form = metadata_page.form
metadata_form['name'] = "Test offer"
+ metadata_form['offer_type'] = models.ConditionalOffer.SITE
benefit_page = metadata_form.submit().follow()
benefit_form = benefit_page.form
@@ -56,7 +57,7 @@ def test_offer_list_page(self):
res = form.submit()
self.assertFalse("No offers found" in res.text)
- form['is_active'] = True
+ form['is_active'] = "true"
res = form.submit()
self.assertFalse("No offers found" in res.text)
@@ -64,7 +65,19 @@ def test_offer_list_page(self):
offer.end_datetime = yesterday
offer.save()
- form['is_active'] = True
+ form['is_active'] = "true"
+ res = form.submit()
+ self.assertTrue("No offers found" in res.text)
+
+ tomorrow = timezone.now() + timezone.timedelta(days=1)
+ offer.end_datetime = tomorrow
+ offer.save()
+
+ form['offer_type'] = "Site"
+ res = form.submit()
+ self.assertFalse("No offers found" in res.text)
+
+ form['offer_type'] = "Voucher"
res = form.submit()
self.assertTrue("No offers found" in res.text)
@@ -77,6 +90,7 @@ def test_can_update_an_existing_offer(self):
metadata_page = detail_page.click(linkid="edit_metadata")
metadata_form = metadata_page.form
metadata_form['name'] = "Offer A+"
+ metadata_form['offer_type'] = models.ConditionalOffer.SITE
benefit_page = metadata_form.submit().follow()
benefit_form = benefit_page.form
@@ -153,6 +167,7 @@ def test_jump_back_to_incentive_step_for_new_offer(self):
metadata_page = list_page.click('Create new offer')
metadata_form = metadata_page.form
metadata_form['name'] = "Test offer"
+ metadata_form['offer_type'] = models.ConditionalOffer.SITE
benefit_page = metadata_form.submit().follow()
benefit_form = benefit_page.form
@@ -174,6 +189,7 @@ def test_jump_back_to_condition_step_for_new_offer(self):
metadata_page = list_page.click('Create new offer')
metadata_form = metadata_page.form
metadata_form['name'] = "Test offer"
+ metadata_form['offer_type'] = models.ConditionalOffer.SITE
benefit_page = metadata_form.submit().follow()
benefit_form = benefit_page.form
@@ -210,3 +226,66 @@ def test_jump_to_condition_step_for_existing_offer(self):
self.assertFalse('range' in condition_page.errors)
self.assertEqual(len(condition_page.errors), 0)
+
+
+class TestOfferListSearch(testcases.WebTestCase):
+ is_staff = True
+
+ TEST_CASES = [
+ ({}, []),
+ (
+ {'name': 'Bob Smith'},
+ ['Name matches "Bob Smith"']
+ ),
+ (
+ {'is_active': True},
+ ['Is active']
+ ),
+ (
+ {'is_active': False},
+ ['Is inactive']
+ ),
+ (
+ {'offer_type': 'Site'},
+ ['Is of type "Site offer - available to all users"']
+ ),
+ (
+ {'has_vouchers': True},
+ ['Has vouchers']
+ ),
+ (
+ {'has_vouchers': False},
+ ['Has no vouchers']
+ ),
+ (
+ {'voucher_code': 'abcd1234'},
+ ['Voucher code matches "abcd1234"']
+ ),
+ (
+ {
+ 'name': 'Bob Smith',
+ 'is_active': True,
+ 'offer_type': 'Site',
+ 'has_vouchers': True,
+ 'voucher_code': 'abcd1234',
+ },
+ [
+ 'Name matches "Bob Smith"',
+ 'Is active',
+ 'Is of type "Site offer - available to all users"',
+ 'Has vouchers',
+ 'Voucher code matches "abcd1234"',
+ ]
+ ),
+ ]
+
+ def test_search_filter_descriptions(self):
+ url = reverse('dashboard:offer-list')
+ for params, expected_filters in self.TEST_CASES:
+ response = self.get(url, params=params)
+ self.assertEqual(response.status_code, 200)
+ applied_filters = [
+ el.text.strip() for el in
+ response.html.select('.search-filter-list .badge')
+ ]
+ self.assertEqual(applied_filters, expected_filters)
diff --git a/tests/functional/dashboard/test_voucher.py b/tests/functional/dashboard/test_voucher.py
new file mode 100644
--- /dev/null
+++ b/tests/functional/dashboard/test_voucher.py
@@ -0,0 +1,76 @@
+from django.urls import reverse
+
+from oscar.test.testcases import WebTestCase
+
+
+class TestVoucherListSearch(WebTestCase):
+ is_staff = True
+
+ TEST_CASES = [
+ ({}, ['Not in a set']),
+ (
+ {'name': 'Bob Smith'},
+ ['Name matches "Bob Smith"']
+ ),
+ (
+ {'code': 'abcd1234'},
+ ['Code is "ABCD1234"']
+ ),
+ (
+ {'offer_name': 'Shipping offer'},
+ ['Offer name matches "Shipping offer"']
+ ),
+ (
+ {'is_active': True},
+ ['Is active']
+ ),
+ (
+ {'is_active': False},
+ ['Is inactive']
+ ),
+ (
+ {'in_set': True},
+ ['In a set']
+ ),
+ (
+ {'in_set': False},
+ ['Not in a set']
+ ),
+ (
+ {'has_offers': True},
+ ['Has offers']
+ ),
+ (
+ {'has_offers': False},
+ ['Has no offers']
+ ),
+ (
+ {
+ 'name': 'Bob Smith',
+ 'code': 'abcd1234',
+ 'offer_name': 'Shipping offer',
+ 'is_active': True,
+ 'in_set': True,
+ 'has_offers': True,
+ },
+ [
+ 'Name matches "Bob Smith"',
+ 'Code is "ABCD1234"',
+ 'Offer name matches "Shipping offer"',
+ 'Is active',
+ 'In a set',
+ 'Has offers',
+ ]
+ ),
+ ]
+
+ def test_search_filter_descriptions(self):
+ url = reverse('dashboard:voucher-list')
+ for params, expected_filters in self.TEST_CASES:
+ response = self.get(url, params=params)
+ self.assertEqual(response.status_code, 200)
+ applied_filters = [
+ el.text.strip() for el in
+ response.html.select('.search-filter-list .badge')
+ ]
+ self.assertEqual(applied_filters, expected_filters)
diff --git a/tests/integration/dashboard/test_offer_views.py b/tests/integration/dashboard/test_offer_views.py
--- a/tests/integration/dashboard/test_offer_views.py
+++ b/tests/integration/dashboard/test_offer_views.py
@@ -1,10 +1,14 @@
-
import pytest
+from django.contrib.messages import get_messages
+from django.urls import reverse
from oscar.apps.dashboard.offers import views as offer_views
from oscar.apps.dashboard.ranges import views as range_views
from oscar.core.loading import get_model
-from oscar.test.factories import catalogue, offer
+from oscar.test.factories.catalogue import ProductFactory
+from oscar.test.factories.offer import ConditionalOfferFactory, RangeFactory
+from oscar.test.factories.voucher import VoucherFactory
+from tests.fixtures import RequestFactory
Range = get_model('offer', 'Range')
ConditionalOffer = get_model('offer', 'ConditionalOffer')
@@ -13,23 +17,23 @@
@pytest.fixture
def many_ranges():
for i in range(0, 30):
- offer.RangeFactory()
+ RangeFactory()
return Range.objects.all()
@pytest.fixture
def many_offers():
for i in range(0, 30):
- offer.ConditionalOfferFactory(
+ ConditionalOfferFactory(
name='Test offer %d' % i
)
@pytest.fixture
def range_with_products():
- productrange = offer.RangeFactory()
+ productrange = RangeFactory()
for i in range(0, 30):
- product = catalogue.ProductFactory()
+ product = ProductFactory()
productrange.add_product(product)
return productrange
@@ -55,6 +59,43 @@ def test_offer_list_view(self, rf, many_offers):
assert response.context_data['page_obj']
assert response.status_code == 200
+ def test_offer_delete_view_for_voucher_offer_without_vouchers(self):
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)
+
+ view = offer_views.OfferDeleteView.as_view()
+
+ request = RequestFactory().get('/')
+ response = view(request, pk=offer.pk)
+ assert response.status_code == 200
+
+ request = RequestFactory().post('/')
+ response = view(request, pk=offer.pk)
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:offer-list')
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == ('success', "Offer deleted!")
+ assert not ConditionalOffer.objects.exists()
+
+ def test_offer_delete_view_for_voucher_offer_with_vouchers(self):
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)
+ VoucherFactory().offers.add(offer)
+
+ view = offer_views.OfferDeleteView.as_view()
+
+ request = RequestFactory().get('/')
+ response = view(request, pk=offer.pk)
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:offer-detail', kwargs={'pk': offer.pk})
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == (
+ 'warning', "This offer can only be deleted if it has no vouchers attached to it")
+
+ request = RequestFactory().post('/')
+ response = view(request, pk=offer.pk)
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:offer-detail', kwargs={'pk': offer.pk})
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == (
+ 'warning', "This offer can only be deleted if it has no vouchers attached to it")
+ assert ConditionalOffer.objects.exists()
+
def test_range_product_list_view(self, rf, range_with_products):
view = range_views.RangeProductListView.as_view()
pk = range_with_products.pk
diff --git a/tests/integration/dashboard/test_voucher_form.py b/tests/integration/dashboard/test_voucher_form.py
--- a/tests/integration/dashboard/test_voucher_form.py
+++ b/tests/integration/dashboard/test_voucher_form.py
@@ -2,10 +2,17 @@
import pytest
from django import test
+from django.urls import reverse
from django.utils import timezone
from oscar.apps.dashboard.vouchers import forms
-from oscar.test.factories.offer import RangeFactory
+from oscar.core.loading import get_model
+from oscar.test.factories.offer import (
+ BenefitFactory, ConditionalOfferFactory, ConditionFactory, RangeFactory)
+from oscar.test.factories.voucher import VoucherSetFactory
+
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
+Voucher = get_model('voucher', 'Voucher')
class TestVoucherForm(test.TestCase):
@@ -16,14 +23,16 @@ def test_doesnt_crash_on_empty_date_fields(self):
exception (instead of just failing validation) when being called with
empty fields. This tests exists to prevent a regression.
"""
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER,
+ benefit=BenefitFactory(range=None),
+ condition=ConditionFactory(range=None, value=1))
data = {
'code': '',
'name': '',
- 'start_date': '',
- 'end_date': '',
- 'benefit_range': '',
- 'benefit_type': 'Percentage',
+ 'start_datetime': '',
+ 'end_datetime': '',
'usage': 'Single use',
+ 'offers': [offer.pk],
}
form = forms.VoucherForm(data=data)
try:
@@ -40,7 +49,9 @@ class TestVoucherSetForm:
def test_valid_form(self):
a_range = RangeFactory(includes_all_products=True)
-
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER,
+ benefit=BenefitFactory(range=a_range),
+ condition=ConditionFactory(range=a_range, value=1))
start = timezone.now()
end = start + timedelta(days=1)
data = {
@@ -50,9 +61,8 @@ def test_valid_form(self):
'start_datetime': start,
'end_datetime': end,
'count': 10,
- 'benefit_range': a_range.pk,
- 'benefit_type': 'Percentage',
- 'benefit_value': 10,
+ 'usage': Voucher.MULTI_USE,
+ 'offers': [offer.pk],
}
form = forms.VoucherSetForm(data=data)
assert form.is_valid()
@@ -60,3 +70,23 @@ def test_valid_form(self):
assert instance.count == instance.vouchers.count()
assert instance.start_datetime == start
assert instance.end_datetime == end
+
+ def test_valid_form_reduced_count(self):
+ voucher_set = VoucherSetFactory(count=5)
+ voucher = voucher_set.vouchers.first()
+ data = {
+ 'name': voucher_set.name,
+ 'code_length': voucher_set.code_length,
+ 'description': voucher_set.description,
+ 'start_datetime': voucher_set.start_datetime,
+ 'end_datetime': voucher_set.end_datetime,
+ 'count': 4,
+ 'usage': voucher.usage,
+ 'offers': voucher.offers.all(),
+ }
+ form = forms.VoucherSetForm(data, instance=voucher_set)
+ assert not form.is_valid()
+ assert form.errors['count'][0] == (
+ 'This cannot be used to delete vouchers (currently 5) in this set. '
+ 'You can do that on the <a href="%s">detail</a> page.') % reverse('dashboard:voucher-set-detail',
+ kwargs={'pk': voucher_set.pk})
diff --git a/tests/integration/dashboard/test_voucher_views.py b/tests/integration/dashboard/test_voucher_views.py
--- a/tests/integration/dashboard/test_voucher_views.py
+++ b/tests/integration/dashboard/test_voucher_views.py
@@ -1,9 +1,15 @@
import pytest
+from django.contrib.messages import get_messages
+from django.urls import reverse
from oscar.apps.dashboard.vouchers import views
from oscar.core.loading import get_model
from oscar.test.factories import voucher
+from oscar.test.factories.offer import ConditionalOfferFactory
+from tests.fixtures import RequestFactory
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
+Voucher = get_model('voucher', 'Voucher')
VoucherSet = get_model('voucher', 'VoucherSet')
@@ -13,6 +19,66 @@ def many_voucher_sets():
return VoucherSet.objects.all()
+@pytest.mark.django_db
+class TestDashboardVouchers:
+
+ def test_voucher_update_view_for_voucher_in_set(self):
+ vs = voucher.VoucherSetFactory(count=10)
+ v = vs.vouchers.first()
+
+ view = views.VoucherUpdateView.as_view()
+
+ request = RequestFactory().get('/')
+ response = view(request, pk=v.pk)
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:voucher-set-update', kwargs={'pk': vs.pk})
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == (
+ 'warning', "The voucher can only be edited as part of its set")
+
+ data = {
+ 'code': v.code,
+ 'name': "New name",
+ 'start_datetime': v.start_datetime,
+ 'end_datetime': v.end_datetime,
+ 'usage': v.usage,
+ 'offers': [v.offers],
+ }
+ request = RequestFactory().post('/', data=data)
+ response = view(request, pk=v.pk)
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:voucher-set-update', kwargs={'pk': vs.pk})
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == (
+ 'warning', "The voucher can only be edited as part of its set")
+ v.refresh_from_db()
+ assert v.name != "New name"
+
+ def test_voucher_delete_view(self):
+ v = voucher.VoucherFactory()
+ v.offers.add(ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER))
+ assert Voucher.objects.count() == 1
+ assert ConditionalOffer.objects.count() == 1
+ request = RequestFactory().post('/')
+ response = views.VoucherDeleteView.as_view()(request, pk=v.pk)
+ assert Voucher.objects.count() == 0
+ # Related offer is not deleted
+ assert ConditionalOffer.objects.count() == 1
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:voucher-list')
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == ('warning', "Voucher deleted")
+
+ def test_voucher_delete_view_for_voucher_in_set(self):
+ vs = voucher.VoucherSetFactory(count=10)
+ assert Voucher.objects.count() == 10
+ request = RequestFactory().post('/')
+ response = views.VoucherDeleteView.as_view()(request, pk=vs.vouchers.first().pk)
+ vs.refresh_from_db()
+ assert vs.count == 9 # "count" is updated
+ assert Voucher.objects.count() == 9
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:voucher-set-detail', kwargs={'pk': vs.pk})
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == ('warning', "Voucher deleted")
+
+
@pytest.mark.django_db
class TestDashboardVoucherSets:
@@ -33,3 +99,15 @@ def test_voucher_set_detail_view(self, rf):
# The view should only list vouchers for vs2
assert len(response.context_data['vouchers']) == 15
assert response.status_code == 200
+
+ def test_voucher_set_delete_view(self):
+ vs = voucher.VoucherSetFactory(count=10)
+ assert VoucherSet.objects.count() == 1
+ assert Voucher.objects.count() == 10
+ request = RequestFactory().post('/')
+ response = views.VoucherSetDeleteView.as_view()(request, pk=vs.pk)
+ assert VoucherSet.objects.count() == 0
+ assert Voucher.objects.count() == 0
+ assert response.status_code == 302
+ assert response.url == reverse('dashboard:voucher-set-list')
+ assert [(m.level_tag, str(m.message)) for m in get_messages(request)][0] == ('warning', "Voucher set deleted")
diff --git a/tests/integration/forms/test_widget.py b/tests/integration/forms/test_widget.py
--- a/tests/integration/forms/test_widget.py
+++ b/tests/integration/forms/test_widget.py
@@ -193,3 +193,9 @@ def test_multiselect_widget_attrs(self):
field = self._get_multiselect_form_field()
attrs = field.widget.get_context(name='my_field', value=None, attrs={})['widget']['attrs']
self.assertEqual(attrs['data-multiple'], 'multiple')
+
+
+class NullBooleanSelectTestCase(TestCase):
+
+ def test_unknown_choice_label(self):
+ self.assertEqual(dict(widgets.NullBooleanSelect().choices)['unknown'], '---------')
diff --git a/tests/integration/offer/test_absolute_benefit.py b/tests/integration/offer/test_absolute_benefit.py
--- a/tests/integration/offer/test_absolute_benefit.py
+++ b/tests/integration/offer/test_absolute_benefit.py
@@ -364,12 +364,14 @@ def test_non_negative_basket_lines_values(self):
value=D('10'))
models.ConditionalOffer.objects.create(
name='offer1',
+ offer_type=models.ConditionalOffer.SITE,
benefit=benefit1,
condition=condition,
exclusive=False
)
models.ConditionalOffer.objects.create(
name='offer2',
+ offer_type=models.ConditionalOffer.SITE,
benefit=benefit2,
condition=condition,
exclusive=False
diff --git a/tests/integration/offer/test_forms.py b/tests/integration/offer/test_forms.py
--- a/tests/integration/offer/test_forms.py
+++ b/tests/integration/offer/test_forms.py
@@ -4,6 +4,34 @@
from django.utils.timezone import now
from oscar.apps.dashboard.offers import forms
+from oscar.apps.offer.models import ConditionalOffer
+from oscar.test.factories import ConditionalOfferFactory, VoucherFactory
+
+
+class TestMetaDataForm(TestCase):
+
+ def test_changing_offer_type_for_voucher_offer_without_vouchers(self):
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)
+ data = {
+ 'name': offer.name,
+ 'description': offer.description,
+ 'offer_type': ConditionalOffer.SITE,
+ }
+ form = forms.MetaDataForm(data, instance=offer)
+ self.assertTrue(form.is_valid())
+
+ def test_changing_offer_type_for_voucher_offer_with_vouchers(self):
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)
+ VoucherFactory().offers.add(offer)
+ data = {
+ 'name': offer.name,
+ 'description': offer.description,
+ 'offer_type': ConditionalOffer.SITE,
+ }
+ form = forms.MetaDataForm(data, instance=offer)
+ self.assertFalse(form.is_valid())
+ self.assertEqual(form.errors['offer_type'][0],
+ "This can only be changed if it has no vouchers attached to it")
class TestRestrictionsFormEnforces(TestCase):
diff --git a/tests/integration/offer/test_priority_offers.py b/tests/integration/offer/test_priority_offers.py
--- a/tests/integration/offer/test_priority_offers.py
+++ b/tests/integration/offer/test_priority_offers.py
@@ -27,6 +27,7 @@ def test_basket_offers_are_ordered(self):
voucher = Voucher.objects.create(
name="Test voucher",
code="test",
+ usage=Voucher.MULTI_USE,
start_datetime=timezone.now(),
end_datetime=timezone.now() + datetime.timedelta(days=12))
diff --git a/tests/integration/voucher/test_forms.py b/tests/integration/voucher/test_forms.py
--- a/tests/integration/voucher/test_forms.py
+++ b/tests/integration/voucher/test_forms.py
@@ -1,15 +1,27 @@
+import datetime
+
import pytest
+from django.utils import timezone
from django.utils.datastructures import MultiValueDict
from oscar.apps.dashboard.vouchers import forms
-from oscar.test.factories.offer import RangeFactory
+from oscar.core.loading import get_model
+from oscar.test.factories.offer import (
+ BenefitFactory, ConditionalOfferFactory, ConditionFactory, RangeFactory)
+from oscar.test.factories.voucher import VoucherSetFactory
+
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
+Voucher = get_model('voucher', 'Voucher')
@pytest.mark.django_db
-def test_voucherform_set_create():
+def test_voucher_set_form_create():
a_range = RangeFactory(
includes_all_products=True
)
+ offer = ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER,
+ benefit=BenefitFactory(range=a_range),
+ condition=ConditionFactory(range=a_range, value=1))
data = MultiValueDict({
'name': ['10% Discount'],
'code_length': ['10'],
@@ -17,11 +29,89 @@ def test_voucherform_set_create():
'description': ['This is a 10% discount for mailing X'],
'start_datetime': ['2014-10-01'],
'end_datetime': ['2018-10-01'],
- 'benefit_range': [a_range.pk],
- 'benefit_type': ['Percentage'],
- 'benefit_value': ['10'],
+ 'usage': [Voucher.MULTI_USE],
+ 'offers': [offer.pk],
})
form = forms.VoucherSetForm(data)
assert form.is_valid(), form.errors
voucher_set = form.save()
assert voucher_set.vouchers.count() == 10
+
+
+@pytest.mark.django_db
+def test_voucher_set_form_update_with_unchanged_count():
+ tzinfo = timezone.get_current_timezone()
+ voucher_set = VoucherSetFactory(name="Dummy name",
+ count=5,
+ code_length=12,
+ description="Dummy description",
+ start_datetime=datetime.datetime(2021, 2, 1, tzinfo=tzinfo),
+ end_datetime=datetime.datetime(2021, 2, 28, tzinfo=tzinfo))
+ voucher = voucher_set.vouchers.first()
+ assert voucher.usage == Voucher.MULTI_USE
+ new_offers = [ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER),
+ ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)]
+ data = {
+ 'name': "New name",
+ 'code_length': 10,
+ 'description': "New description",
+ 'start_datetime': datetime.datetime(2021, 3, 1, tzinfo=tzinfo),
+ 'end_datetime': datetime.datetime(2021, 3, 31, tzinfo=tzinfo),
+ 'count': voucher_set.count,
+ 'usage': Voucher.SINGLE_USE,
+ 'offers': new_offers,
+ }
+ form = forms.VoucherSetForm(data, instance=voucher_set)
+ assert form.is_valid(), form.errors
+ voucher_set = form.save()
+ assert voucher_set.vouchers.count() == 5
+ for i, v in enumerate(voucher_set.vouchers.order_by('date_created')):
+ assert v.name == "New name - %d" % (i + 1)
+ assert len(v.code) == 14 # The code is not modified
+ assert v.start_datetime == datetime.datetime(2021, 3, 1, tzinfo=tzinfo)
+ assert v.end_datetime == datetime.datetime(2021, 3, 31, tzinfo=tzinfo)
+ assert v.usage == Voucher.SINGLE_USE
+ assert list(v.offers.all()) == new_offers
+
+
+@pytest.mark.django_db
+def test_voucher_set_form_update_with_changed_count():
+ tzinfo = timezone.get_current_timezone()
+ voucher_set = VoucherSetFactory(name="Dummy name",
+ count=5,
+ code_length=12,
+ description="Dummy description",
+ start_datetime=datetime.datetime(2021, 2, 1, tzinfo=tzinfo),
+ end_datetime=datetime.datetime(2021, 2, 28, tzinfo=tzinfo))
+ voucher = voucher_set.vouchers.first()
+ assert voucher.usage == Voucher.MULTI_USE
+ new_offers = [ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER),
+ ConditionalOfferFactory(offer_type=ConditionalOffer.VOUCHER)]
+ data = {
+ 'name': "New name",
+ 'code_length': 10,
+ 'description': "New description",
+ 'start_datetime': datetime.datetime(2021, 3, 1, tzinfo=tzinfo),
+ 'end_datetime': datetime.datetime(2021, 3, 31, tzinfo=tzinfo),
+ 'count': 10,
+ 'usage': Voucher.SINGLE_USE,
+ 'offers': new_offers,
+ }
+ form = forms.VoucherSetForm(data, instance=voucher_set)
+ assert form.is_valid(), form.errors
+ voucher_set = form.save()
+ voucher_set.refresh_from_db()
+ assert voucher_set.count == 10 # "count" is updated
+ assert voucher_set.vouchers.count() == 10
+ for i, v in enumerate(voucher_set.vouchers.order_by('date_created')):
+ assert v.name == "New name - %d" % (i + 1)
+ if i < 5:
+ # Original vouchers
+ assert len(v.code) == 14 # The code is not modified
+ else:
+ # New vouchers
+ assert len(v.code) == 12
+ assert v.start_datetime == datetime.datetime(2021, 3, 1, tzinfo=tzinfo)
+ assert v.end_datetime == datetime.datetime(2021, 3, 31, tzinfo=tzinfo)
+ assert v.usage == Voucher.SINGLE_USE
+ assert list(v.offers.all()) == new_offers
diff --git a/tests/integration/voucher/test_models.py b/tests/integration/voucher/test_models.py
--- a/tests/integration/voucher/test_models.py
+++ b/tests/integration/voucher/test_models.py
@@ -5,7 +5,6 @@
from django.core import exceptions
from django.test import TestCase
from django.utils.timezone import utc
-from django.utils.translation import gettext_lazy as _
from oscar.apps.voucher.models import Voucher
from oscar.core.compat import get_user_model
@@ -108,85 +107,6 @@ def setUp(self):
self.offer_range = RangeFactory(products=[product])
self.offer_condition = ConditionFactory(range=self.offer_range, value=2)
- def test_related_offer_deleted(self):
- # Voucher with offer name corresponding to it as used in the dashboard
- voucher_name = "Voucher"
- voucher = VoucherFactory(name=voucher_name, code="VOUCHER")
- voucher.offers.add(
- create_offer(
- name=_("Offer for voucher '%s'") % voucher_name,
- offer_type='Voucher',
- range=self.offer_range,
- condition=self.offer_condition
- )
- )
-
- voucher.delete()
- self.assertFalse(
- ConditionalOffer.objects.filter(
- name=_("Offer for voucher '%s'") % voucher_name,
- offer_type=ConditionalOffer.VOUCHER
- ).exists())
-
- def test_related_offer_different_name_not_deleted(self):
- # Voucher with offer named differently
- voucher = VoucherFactory(name="Voucher", code="VOUCHER")
- voucher.offers.add(
- create_offer(
- name="Different name test",
- offer_type='Voucher',
- range=self.offer_range,
- condition=self.offer_condition
- )
- )
-
- offer_ids = list(voucher.offers.all().values_list('pk', flat=True))
-
- voucher.delete()
- count_offers = ConditionalOffer.objects.filter(id__in=offer_ids).count()
- assert len(offer_ids) == count_offers
-
- def test_related_offer_different_type_not_deleted(self):
- # Voucher with offer not of type "Voucher"
- voucher_name = "Voucher"
- voucher = VoucherFactory(name=voucher_name, code="VOUCHER")
- voucher.offers.add(
- create_offer(
- name=_("Offer for voucher '%s'") % voucher_name,
- offer_type='Site',
- range=self.offer_range,
- condition=self.offer_condition
- )
- )
-
- offer_ids = list(voucher.offers.all().values_list('pk', flat=True))
-
- voucher.delete()
- count_offers = ConditionalOffer.objects.filter(id__in=offer_ids).count()
- assert len(offer_ids) == count_offers
-
- def test_multiple_related_offers_not_deleted(self):
- # Voucher with already used offer
- voucher_name = "Voucher 1"
- offer = create_offer(
- name=_("Offer for voucher '%s'") % voucher_name,
- offer_type='Voucher',
- range=self.offer_range,
- condition=self.offer_condition
- )
-
- voucher1 = VoucherFactory(name=voucher_name, code="VOUCHER1")
- voucher1.offers.add(offer)
-
- voucher2 = VoucherFactory(name="Voucher 2", code="VOUCHER2")
- voucher2.offers.add(offer)
-
- offer_ids = list(voucher1.offers.all().values_list('pk', flat=True))
-
- voucher1.delete()
- count_offers = ConditionalOffer.objects.filter(id__in=offer_ids).count()
- assert len(offer_ids) == count_offers
-
class TestAvailableForBasket(TestCase):
@@ -214,19 +134,21 @@ class TestVoucherSet(object):
def test_factory(self):
voucherset = VoucherSetFactory()
assert voucherset.count == voucherset.vouchers.count()
- code = voucherset.vouchers.first().code
- assert len(code) == 14
- assert code.count('-') == 2
assert str(voucherset) == voucherset.name
- assert voucherset.offer
+ offers = voucherset.vouchers.first().offers.all()
for voucher in voucherset.vouchers.all():
- assert voucherset.offer in voucher.offers.all()
+ assert len(voucher.code) == 14
+ assert voucher.code.count('-') == 2
+ list(voucher.offers.all()) == list(offers)
+ assert voucher.offers.count() == 1
+ assert voucher.offers.filter(offer_type=ConditionalOffer.VOUCHER).count() == 1
- def test_min_count(self):
+ def test_update_count(self):
voucherset = VoucherSetFactory(count=20)
assert voucherset.count == 20
voucherset.count = 10
voucherset.save()
+ voucherset.update_count()
voucherset.refresh_from_db()
assert voucherset.count == 20
| Refactor voucher creation in the dashboard to allow greater flexibility
### Issue Summary
The voucher app provides a very flexible implementation of voucher functionality, where multiple offers can be associated with a voucher. But the dashboard interface for managing vouchers hides this flexibility and only allows the creation of vouchers with a single offer. Meanwhile, on the offer side, only site-wide offers can be created and edited through the dashboard.
### Proposal
I propose to refactor the voucher functionality as follows:
1. Allow CRUD of all types of offer in the dashboard, making it easy to identify the type of the offer (site-wide, voucher, session, user). We can provide a tabbed interface to see the offers of each type.
(By default, session and user offers are not applied anywhere - a future enhancement would be to allow associating user offers with particular users/groups of users, instead of requiring projects to implement this themselves.)
2. Refactor the existing voucher creation functionality so that instead of creating a single offer on the fly, the administrator instead selects one or more existing offers (of type voucher) to add to the voucher. This allows the creation of complex vouchers with a combination of offers.
This provides a much more powerful and flexible interface to the voucher functionality that already exists.
TypeError creating voucher without end-date
In oscar 3.0 beta/master, creating a coupon/voucher , not specifying an end date results in
> TypeError: '>' not supported between instances of 'datetime.datetime' and 'NoneType'
| Agree.
Yes that would be nice
| "2021-01-29T13:58:25Z" | 3.0 | [] | [
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_delete_view_for_voucher_offer_with_vouchers",
"tests/integration/dashboard/test_voucher_form.py::TestVoucherSetForm::test_valid_form",
"tests/integration/dashboard/test_voucher_form.py::TestVoucherSetForm::test_valid_form_reduced_count",
"tests/integration/dashboard/test_voucher_views.py::TestDashboardVouchers::test_voucher_update_view_for_voucher_in_set",
"tests/integration/dashboard/test_voucher_views.py::TestDashboardVouchers::test_voucher_delete_view_for_voucher_in_set",
"tests/integration/dashboard/test_voucher_views.py::TestDashboardVoucherSets::test_voucher_set_detail_view",
"tests/integration/dashboard/test_voucher_views.py::TestDashboardVoucherSets::test_voucher_set_delete_view",
"tests/integration/voucher/test_forms.py::test_voucher_set_form_create",
"tests/integration/voucher/test_forms.py::test_voucher_set_form_update_with_unchanged_count",
"tests/integration/voucher/test_forms.py::test_voucher_set_form_update_with_changed_count",
"tests/integration/voucher/test_models.py::TestVoucherSet::test_factory",
"tests/integration/voucher/test_models.py::TestVoucherSet::test_update_count",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForStaffUser::test_has_stats_vars_in_context",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_create_an_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_update_an_existing_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_back_to_condition_step_for_new_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_back_to_incentive_step_for_new_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_offer_list_page",
"tests/integration/forms/test_widget.py::NullBooleanSelectTestCase::test_unknown_choice_label",
"tests/integration/offer/test_forms.py::TestMetaDataForm::test_changing_offer_type_for_voucher_offer_with_vouchers"
] | [
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_range_list_view",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_list_view",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_delete_view_for_voucher_offer_without_vouchers",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_range_product_list_view",
"tests/integration/dashboard/test_voucher_views.py::TestDashboardVouchers::test_voucher_delete_view",
"tests/integration/dashboard/test_voucher_views.py::TestDashboardVoucherSets::test_voucher_set_list_view",
"tests/integration/voucher/test_models.py::TestVoucherSet::test_num_basket_additions",
"tests/integration/voucher/test_models.py::TestVoucherSet::test_num_orders",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForAnonUser::test_is_not_available",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForStaffUser::test_includes_hourly_report_with_no_orders",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForStaffUser::test_includes_hourly_report_with_orders",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForStaffUser::test_is_available",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForStaffUser::test_login_redirects_to_dashboard_index",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForPartnerUser::test_is_available",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForPartnerUser::test_is_not_available",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexForPartnerUser::test_stats",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexStatsForNonStaffUser::test_partner1",
"tests/functional/dashboard/test_dashboard.py::TestDashboardIndexStatsForNonStaffUser::test_partner2",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_change_offer_priority",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_jump_to_intermediate_step_for_existing_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_reinstate_a_suspended_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_suspend_an_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_update_an_existing_offer_save_directly",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_cannot_jump_to_intermediate_step",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_to_condition_step_for_existing_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_to_incentive_step_for_existing_offer",
"tests/integration/dashboard/test_voucher_form.py::TestVoucherForm::test_doesnt_crash_on_empty_date_fields",
"tests/integration/forms/test_widget.py::ImageInputTestCase::test_bound_context",
"tests/integration/forms/test_widget.py::ImageInputTestCase::test_unbound_context",
"tests/integration/forms/test_widget.py::TimePickerInputTestCase::test_div_attrs_context",
"tests/integration/forms/test_widget.py::TimePickerInputTestCase::test_icon_classes_context",
"tests/integration/forms/test_widget.py::TimePickerInputTestCase::test_input_format_unicode",
"tests/integration/forms/test_widget.py::DatePickerInputTestCase::test_datepickerinput_format_unicode",
"tests/integration/forms/test_widget.py::DatePickerInputTestCase::test_div_attrs_context",
"tests/integration/forms/test_widget.py::DatePickerInputTestCase::test_icon_classes_context",
"tests/integration/forms/test_widget.py::DateTimePickerInputTestCase::test_datetimepickerinput_format_unicode",
"tests/integration/forms/test_widget.py::DateTimePickerInputTestCase::test_div_attrs_context",
"tests/integration/forms/test_widget.py::DateTimePickerInputTestCase::test_icon_classes_context",
"tests/integration/forms/test_widget.py::TestWidgetsDatetimeFormat::test_datetime_to_date_format_conversion",
"tests/integration/forms/test_widget.py::TestWidgetsDatetimeFormat::test_datetime_to_time_format_conversion",
"tests/integration/forms/test_widget.py::AdvancedSelectWidgetTestCase::test_widget_disabled_options",
"tests/integration/forms/test_widget.py::RemoteSelectTestCase::test_multiselect_widget_attrs",
"tests/integration/forms/test_widget.py::RemoteSelectTestCase::test_multiselect_widget_renders_only_selected_choices",
"tests/integration/forms/test_widget.py::RemoteSelectTestCase::test_not_required_widget_attrs",
"tests/integration/forms/test_widget.py::RemoteSelectTestCase::test_remote_url_required",
"tests/integration/forms/test_widget.py::RemoteSelectTestCase::test_select_widget_renders_only_selected_choices",
"tests/integration/forms/test_widget.py::RemoteSelectTestCase::test_widget_attrs",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountConditionOnDifferentRange::test_condition_is_consumed_correctly",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountConditionOnDifferentRange::test_succcessful_application_consumes_correctly",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountCondition::test_applies_basket_exceeding_condition_smaller_prices_than_discount_higher_prices_first",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountCondition::test_applies_correctly_to_basket_which_exceeds_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountCondition::test_applies_correctly_to_basket_which_exceeds_condition_with_smaller_prices_than_discount",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountCondition::test_applies_correctly_to_basket_which_matches_condition_with_multiple_lines",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountCondition::test_applies_correctly_to_basket_which_matches_condition_with_multiple_lines_and_lower_total_value",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountCondition::test_applies_correctly_to_basket_which_matches_condition_with_one_line",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithCountCondition::test_applies_correctly_to_empty_basket",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscount::test_applies_correctly_when_discounts_need_rounding",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithCountCondition::test_applies_correctly_to_basket_which_exceeds_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithCountCondition::test_applies_correctly_to_basket_which_exceeds_condition_but_with_smaller_prices_than_discount",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithCountCondition::test_applies_correctly_to_basket_which_matches_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithCountCondition::test_applies_correctly_to_empty_basket",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithValueCondition::test_applies_correctly_to_empty_basket",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithValueCondition::test_applies_correctly_to_multi_item_basket_which_exceeds_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithValueCondition::test_applies_correctly_to_multi_item_basket_which_exceeds_condition_but_matches_boundary",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithValueCondition::test_applies_correctly_to_multi_item_basket_which_matches_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountAppliedWithValueCondition::test_applies_correctly_to_single_item_basket_which_matches_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithValueCondition::test_applies_correctly_to_empty_basket",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithValueCondition::test_applies_correctly_to_multi_item_basket_which_exceeds_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithValueCondition::test_applies_correctly_to_multi_item_basket_which_exceeds_condition_but_matches_boundary",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithValueCondition::test_applies_correctly_to_multi_item_basket_which_matches_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithValueCondition::test_applies_correctly_to_multi_item_basket_which_matches_condition_but_with_lower_prices_than_discount",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountWithMaxItemsSetAppliedWithValueCondition::test_applies_correctly_to_single_item_basket_which_matches_condition",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountBenefit::test_non_negative_basket_lines_values",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountBenefit::test_requires_a_benefit_value",
"tests/integration/offer/test_absolute_benefit.py::TestAnAbsoluteDiscountBenefit::test_requires_a_range",
"tests/integration/offer/test_forms.py::TestMetaDataForm::test_changing_offer_type_for_voucher_offer_without_vouchers",
"tests/integration/offer/test_forms.py::TestRestrictionsFormEnforces::test_cronological_dates",
"tests/integration/offer/test_priority_offers.py::TestPriorityOffers::test_basket_offers_are_ordered",
"tests/integration/offer/test_priority_offers.py::TestPriorityOffers::test_site_offers_are_ordered",
"tests/integration/voucher/test_models.py::TestSavingAVoucher::test_saves_code_as_uppercase",
"tests/integration/voucher/test_models.py::TestSavingAVoucher::test_verifies_dates_are_sensible",
"tests/integration/voucher/test_models.py::TestAVoucher::test_increments_total_discount_when_recording_usage",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_active_between_start_and_end_dates",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_active_on_end_date",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_active_on_start_date",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_inactive_outside_of_start_and_end_dates",
"tests/integration/voucher/test_models.py::TestMultiuseVoucher::test_is_available_to_same_user_multiple_times",
"tests/integration/voucher/test_models.py::TestOncePerCustomerVoucher::test_is_available_to_a_user_once",
"tests/integration/voucher/test_models.py::TestOncePerCustomerVoucher::test_is_available_to_different_users",
"tests/integration/voucher/test_models.py::TestAvailableForBasket::test_is_available_for_basket"
] | 04cd6a4fc750db9310147d96776f06fe289269bf |
django-oscar/django-oscar | 4,017 | django-oscar__django-oscar-4017 | [
"3811"
] | 44ce5c3bdea808ca1eb8bb1a6dde0ccb8d4f8d98 | diff --git a/src/oscar/apps/dashboard/offers/forms.py b/src/oscar/apps/dashboard/offers/forms.py
--- a/src/oscar/apps/dashboard/offers/forms.py
+++ b/src/oscar/apps/dashboard/offers/forms.py
@@ -74,6 +74,9 @@ def save(self, *args, **kwargs):
"""
instance = super().save(*args, **kwargs)
if instance.id:
+ for offer in instance.combinations.all():
+ if offer not in self.cleaned_data['combinations']:
+ offer.combinations.remove(instance)
instance.combinations.clear()
for offer in self.cleaned_data['combinations']:
if offer != instance:
| diff --git a/tests/functional/dashboard/test_offer.py b/tests/functional/dashboard/test_offer.py
--- a/tests/functional/dashboard/test_offer.py
+++ b/tests/functional/dashboard/test_offer.py
@@ -227,6 +227,27 @@ def test_jump_to_condition_step_for_existing_offer(self):
self.assertFalse('range' in condition_page.errors)
self.assertEqual(len(condition_page.errors), 0)
+ def test_remove_offer_from_combinations(self):
+ offer_a = factories.create_offer("Offer A")
+ offer_b = factories.create_offer("Offer B")
+ offer_b.exclusive = False
+ offer_b.save()
+
+ restrictions_page = self.get(reverse(
+ 'dashboard:offer-restrictions', kwargs={'pk': offer_a.pk}))
+ restrictions_page.form['exclusive'] = False
+ restrictions_page.form['combinations'] = [offer_b.id]
+ restrictions_page.form.submit()
+
+ self.assertIn(offer_a, offer_b.combinations.all())
+
+ restrictions_page = self.get(reverse(
+ 'dashboard:offer-restrictions', kwargs={'pk': offer_a.pk}))
+ restrictions_page.form['combinations'] = []
+ restrictions_page.form.submit()
+
+ self.assertNotIn(offer_a, offer_b.combinations.all())
+
class TestOfferListSearch(testcases.WebTestCase):
is_staff = True
| Offer Combination Removal Issue
### Issue Summary
Removing an offer combination does not remove the offer combination from both the current offer being saved and the offer that was combined.
### Steps to Reproduce
1. Create 2 non-exclusive Offers (Offer A and Offer B)
2. Add Offer A as a Combination on Offer B, save
3. Go to Offer A, can see that Offer B is a "Combined Offer", remove Offer B from Offer A combinations
4. Go to Offer B, can see that Offer A is still a Combined Offer
### Examples on Oscar sandbox
**Setup**
![image](https://user-images.githubusercontent.com/674282/143189491-c4faaafa-3fac-4920-a556-9fba8c66c4a4.png)
![image](https://user-images.githubusercontent.com/674282/143189552-16171e97-0389-43d4-86b1-1988544aaf83.png)
**Remove the Offer B Combination from Offer A**
![image](https://user-images.githubusercontent.com/674282/143189663-56da3f38-551f-4dc2-b62c-469527fce17f.png)
![image](https://user-images.githubusercontent.com/674282/143189732-17f30d37-60c6-499e-966b-133757efc431.png)
| Is anyone working on this issue? If not could I take this up? @solarissmoke
@SakshiUppoor please do!
Thanks!
I think adding a loop to find any removed offers and detaching the instance from combination offer fields of these offers should fix this issue.
https://github.com/django-oscar/django-oscar/blob/dd200b8ea31078b953bdcc49d8f1a91d7733548a/src/oscar/apps/dashboard/offers/forms.py#L76-L89
Will get started with a PR | "2022-11-30T18:46:23Z" | 3.2 | [] | [
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_remove_offer_from_combinations"
] | [
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_change_offer_priority",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_create_an_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_jump_to_intermediate_step_for_existing_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_reinstate_a_suspended_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_suspend_an_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_update_an_existing_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_can_update_an_existing_offer_save_directly",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_cannot_jump_to_intermediate_step",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_back_to_condition_step_for_new_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_back_to_incentive_step_for_new_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_to_condition_step_for_existing_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_jump_to_incentive_step_for_existing_offer",
"tests/functional/dashboard/test_offer.py::TestAnAdmin::test_offer_list_page",
"tests/functional/dashboard/test_offer.py::TestOfferListSearch::test_search_filter_descriptions"
] | c862b4c8d75d2847c884f866a0919ed2b15ba8a8 |
django-oscar/django-oscar | 3,393 | django-oscar__django-oscar-3393 | [
"3382"
] | 386244068de4a175af753007b181cb193bc28192 | diff --git a/src/oscar/apps/checkout/views.py b/src/oscar/apps/checkout/views.py
--- a/src/oscar/apps/checkout/views.py
+++ b/src/oscar/apps/checkout/views.py
@@ -608,9 +608,9 @@ def submit(self, user, basket, shipping_address, shipping_method, # noqa (too c
except Exception as e:
# Unhandled exception - hopefully, you will only ever see this in
# development...
- logger.error(
+ logger.exception(
"Order #%s: unhandled exception while taking payment (%s)",
- order_number, e, exc_info=True)
+ order_number, e)
self.restore_frozen_basket()
return self.render_preview(
self.request, error=error_msg, **payment_kwargs)
@@ -635,6 +635,12 @@ def submit(self, user, basket, shipping_address, shipping_method, # noqa (too c
self.restore_frozen_basket()
return self.render_preview(
self.request, error=msg, **payment_kwargs)
+ except Exception as e:
+ # Hopefully you only ever reach this in development
+ logger.exception("Order #%s: unhandled exception while placing order (%s)", order_number, e)
+ error_msg = _("A problem occurred while placing this order. Please contact customer services.")
+ self.restore_frozen_basket()
+ return self.render_preview(self.request, error=error_msg, **payment_kwargs)
def get_template_names(self):
return [self.template_name_preview] if self.preview else [
| diff --git a/tests/functional/checkout/test_guest_checkout.py b/tests/functional/checkout/test_guest_checkout.py
--- a/tests/functional/checkout/test_guest_checkout.py
+++ b/tests/functional/checkout/test_guest_checkout.py
@@ -399,7 +399,7 @@ def test_handles_bad_errors_during_payments(
preview = self.ready_to_place_an_order(is_guest=True)
response = preview.forms['place_order_form'].submit()
self.assertIsOk(response)
- self.assertTrue(mock_logger.error.called)
+ self.assertTrue(mock_logger.exception.called)
basket = Basket.objects.get()
self.assertEqual(basket.status, Basket.OPEN)
@@ -416,6 +416,17 @@ def test_handles_unexpected_order_placement_errors_gracefully(
basket = Basket.objects.get()
self.assertEqual(basket.status, Basket.OPEN)
+ @mock.patch('oscar.apps.checkout.views.logger')
+ @mock.patch('oscar.apps.checkout.views.PaymentDetailsView.handle_order_placement')
+ def test_handles_all_other_exceptions_gracefully(self, mock_method, mock_logger):
+ mock_method.side_effect = Exception()
+ preview = self.ready_to_place_an_order(is_guest=True)
+ response = preview.forms['place_order_form'].submit()
+ self.assertIsOk(response)
+ self.assertTrue(mock_logger.exception.called)
+ basket = Basket.objects.get()
+ self.assertEqual(basket.status, Basket.OPEN)
+
@override_settings(OSCAR_ALLOW_ANON_CHECKOUT=True)
class TestPaymentDetailsWithPreview(CheckoutMixin, WebTestCase):
| Baskets can be stuck frozen
Found a bug? Please fill out the sections below.
### Issue Summary
If `self.handle_order_placement` has an exception besides `UnableToPlaceOrder`, the `restore_frozen_basket` method is never called.
### Steps to Reproduce
In my example, I overrode `OrderCreator.create_line_models` and had a rare error in there.
### Technical details
* Python version: 2.7.
* Django version: 1.11.
* Oscar version: 1.6.7.
###
I recognize this is not the latest version, and we're doing something a little outside of the norm. That said, `restore_frozen_basket` should probably be in a `finally` clause.
| Yeah, makes sense - we basically need to [duplicate this logic](https://github.com/django-oscar/django-oscar/blob/05e4594230013c50ddafdf7458d51fc4b71277b3/src/oscar/apps/checkout/views.py#L608-L616) in the try/except block for `handle_order_placement`. | "2020-06-07T06:10:05Z" | 2.1 | [] | [
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_handles_all_other_exceptions_gracefully",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_handles_bad_errors_during_payments"
] | [
"tests/functional/checkout/test_guest_checkout.py::TestIndexView::test_prefill_form_with_email_for_returning_guest",
"tests/functional/checkout/test_guest_checkout.py::TestIndexView::test_redirects_customers_with_empty_basket",
"tests/functional/checkout/test_guest_checkout.py::TestIndexView::test_redirects_customers_with_invalid_basket",
"tests/functional/checkout/test_guest_checkout.py::TestIndexView::test_redirects_existing_customers_to_shipping_address_page",
"tests/functional/checkout/test_guest_checkout.py::TestIndexView::test_redirects_guest_customers_to_shipping_address_page",
"tests/functional/checkout/test_guest_checkout.py::TestIndexView::test_redirects_new_customers_to_registration_page",
"tests/functional/checkout/test_guest_checkout.py::TestShippingAddressView::test_redirects_customers_who_have_skipped_guest_form",
"tests/functional/checkout/test_guest_checkout.py::TestShippingAddressView::test_redirects_customers_whose_basket_doesnt_require_shipping",
"tests/functional/checkout/test_guest_checkout.py::TestShippingAddressView::test_redirects_customers_with_empty_basket",
"tests/functional/checkout/test_guest_checkout.py::TestShippingAddressView::test_redirects_customers_with_invalid_basket",
"tests/functional/checkout/test_guest_checkout.py::TestShippingAddressView::test_shows_initial_data_if_the_form_has_already_been_submitted",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_check_user_can_submit_only_valid_shipping_method",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_redirects_customers_when_no_shipping_methods_available",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_redirects_customers_when_only_one_shipping_method_is_available",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_redirects_customers_who_have_skipped_guest_form",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_redirects_customers_who_have_skipped_shipping_address_form",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_redirects_customers_whose_basket_doesnt_require_shipping",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_redirects_customers_with_empty_basket",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_redirects_customers_with_invalid_basket",
"tests/functional/checkout/test_guest_checkout.py::TestShippingMethodView::test_shows_form_when_multiple_shipping_methods_available",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentMethodView::test_redirects_customers_who_have_skipped_guest_form",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentMethodView::test_redirects_customers_who_have_skipped_shipping_address_form",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentMethodView::test_redirects_customers_who_have_skipped_shipping_method_step",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentMethodView::test_redirects_customers_with_empty_basket",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentMethodView::test_redirects_customers_with_invalid_basket",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_handles_anticipated_payments_errors_gracefully",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_handles_unexpected_order_placement_errors_gracefully",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_handles_unexpected_payment_errors_gracefully",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_redirects_customers_when_using_bank_gateway",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_redirects_customers_who_have_skipped_guest_form",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_redirects_customers_who_have_skipped_shipping_address_form",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_redirects_customers_who_have_skipped_shipping_method_step",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_redirects_customers_with_empty_basket",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsView::test_redirects_customers_with_invalid_basket",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsWithPreview::test_handles_invalid_payment_forms",
"tests/functional/checkout/test_guest_checkout.py::TestPaymentDetailsWithPreview::test_payment_form_being_submitted_from_payment_details_view",
"tests/functional/checkout/test_guest_checkout.py::TestPlacingOrder::test_saves_guest_email_with_order"
] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,019 | django-oscar__django-oscar-3019 | [
"1962"
] | f992506003f73fa5d8444cdfee0a2bab209e10b0 | diff --git a/src/oscar/apps/dashboard/catalogue/forms.py b/src/oscar/apps/dashboard/catalogue/forms.py
--- a/src/oscar/apps/dashboard/catalogue/forms.py
+++ b/src/oscar/apps/dashboard/catalogue/forms.py
@@ -80,7 +80,7 @@ def __init__(self, product_class, user, *args, **kwargs):
if field_name in self.fields:
del self.fields[field_name]
else:
- for field_name in ['price_excl_tax', 'num_in_stock']:
+ for field_name in ['price', 'num_in_stock']:
if field_name in self.fields:
self.fields[field_name].required = True
@@ -88,7 +88,7 @@ class Meta:
model = StockRecord
fields = [
'partner', 'partner_sku',
- 'price_currency', 'price_excl_tax', 'price_retail', 'cost_price',
+ 'price_currency', 'price',
'num_in_stock', 'low_stock_threshold',
]
diff --git a/src/oscar/apps/order/abstract_models.py b/src/oscar/apps/order/abstract_models.py
--- a/src/oscar/apps/order/abstract_models.py
+++ b/src/oscar/apps/order/abstract_models.py
@@ -543,10 +543,6 @@ class AbstractLine(models.Model):
_("Price before discounts (excl. tax)"),
decimal_places=2, max_digits=12)
- # Deprecated - will be removed in Oscar 2.1
- unit_cost_price = models.DecimalField(
- _("Unit Cost Price"), decimal_places=2, max_digits=12, blank=True,
- null=True)
# Normal site price for item (without discounts)
unit_price_incl_tax = models.DecimalField(
_("Unit Price (inc. tax)"), decimal_places=2, max_digits=12,
@@ -554,19 +550,11 @@ class AbstractLine(models.Model):
unit_price_excl_tax = models.DecimalField(
_("Unit Price (excl. tax)"), decimal_places=2, max_digits=12,
blank=True, null=True)
- # Deprecated - will be removed in Oscar 2.1
- unit_retail_price = models.DecimalField(
- _("Unit Retail Price"), decimal_places=2, max_digits=12,
- blank=True, null=True)
# Partners often want to assign some status to each line to help with their
# own business processes.
status = models.CharField(_("Status"), max_length=255, blank=True)
- # Deprecated - will be removed in Oscar 2.1
- est_dispatch_date = models.DateField(
- _("Estimated Dispatch Date"), blank=True, null=True)
-
#: Order status pipeline. This should be a dict where each (key, value)
#: corresponds to a status and the possible statuses that can follow that
#: one.
diff --git a/src/oscar/apps/order/migrations/0010_auto_20200724_0909.py b/src/oscar/apps/order/migrations/0010_auto_20200724_0909.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/order/migrations/0010_auto_20200724_0909.py
@@ -0,0 +1,25 @@
+# Generated by Django 2.2.10 on 2020-07-24 08:09
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0009_surcharge'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='line',
+ name='est_dispatch_date',
+ ),
+ migrations.RemoveField(
+ model_name='line',
+ name='unit_cost_price',
+ ),
+ migrations.RemoveField(
+ model_name='line',
+ name='unit_retail_price',
+ ),
+ ]
diff --git a/src/oscar/apps/order/utils.py b/src/oscar/apps/order/utils.py
--- a/src/oscar/apps/order/utils.py
+++ b/src/oscar/apps/order/utils.py
@@ -179,13 +179,8 @@ def create_line_models(self, order, basket_line, extra_line_fields=None):
'line_price_before_discounts_incl_tax':
basket_line.line_price_incl_tax,
# Reporting details
- 'unit_cost_price': stockrecord.cost_price,
'unit_price_incl_tax': basket_line.unit_price_incl_tax,
'unit_price_excl_tax': basket_line.unit_price_excl_tax,
- 'unit_retail_price': stockrecord.price_retail,
- # Shipping details
- 'est_dispatch_date':
- basket_line.purchase_info.availability.dispatch_date
}
extra_line_fields = extra_line_fields or {}
if hasattr(settings, 'OSCAR_INITIAL_LINE_STATUS'):
diff --git a/src/oscar/apps/partner/abstract_models.py b/src/oscar/apps/partner/abstract_models.py
--- a/src/oscar/apps/partner/abstract_models.py
+++ b/src/oscar/apps/partner/abstract_models.py
@@ -109,24 +109,12 @@ class AbstractStockRecord(models.Model):
price_currency = models.CharField(
_("Currency"), max_length=12, default=get_default_currency)
- # This is the base price for calculations - tax should be applied by the
- # appropriate method. We don't store tax here as its calculation is highly
- # domain-specific. It is NULLable because some items don't have a fixed
- # price but require a runtime calculation (possible from an external
- # service). Current field name `price_excl_tax` is deprecated and will be
- # renamed into `price` in Oscar 2.1.
- price_excl_tax = models.DecimalField(
- _("Price (excl. tax)"), decimal_places=2, max_digits=12,
- blank=True, null=True)
-
- # Deprecated - will be removed in Oscar 2.1
- price_retail = models.DecimalField(
- _("Price (retail)"), decimal_places=2, max_digits=12,
- blank=True, null=True)
-
- # Deprecated - will be removed in Oscar 2.1
- cost_price = models.DecimalField(
- _("Cost Price"), decimal_places=2, max_digits=12,
+ # This is the base price for calculations - whether this is inclusive or exclusive of
+ # tax depends on your implementation, as this is highly domain-specific.
+ # It is nullable because some items don't have a fixed
+ # price but require a runtime calculation (possibly from an external service).
+ price = models.DecimalField(
+ _("Price"), decimal_places=2, max_digits=12,
blank=True, null=True)
#: Number of items in stock
diff --git a/src/oscar/apps/partner/admin.py b/src/oscar/apps/partner/admin.py
--- a/src/oscar/apps/partner/admin.py
+++ b/src/oscar/apps/partner/admin.py
@@ -7,7 +7,7 @@
class StockRecordAdmin(admin.ModelAdmin):
- list_display = ('product', 'partner', 'partner_sku', 'price_excl_tax', 'num_in_stock')
+ list_display = ('product', 'partner', 'partner_sku', 'price', 'num_in_stock')
list_filter = ('partner',)
diff --git a/src/oscar/apps/partner/importers.py b/src/oscar/apps/partner/importers.py
--- a/src/oscar/apps/partner/importers.py
+++ b/src/oscar/apps/partner/importers.py
@@ -101,8 +101,7 @@ def _create_item(self, product_class, category_str, upc, title,
return item
- def _create_stockrecord(self, item, partner_name, partner_sku,
- price_excl_tax, num_in_stock, stats):
+ def _create_stockrecord(self, item, partner_name, partner_sku, price, num_in_stock, stats):
# Create partner and stock record
partner, _ = Partner.objects.get_or_create(
name=partner_name)
@@ -114,7 +113,7 @@ def _create_stockrecord(self, item, partner_name, partner_sku,
stock.product = item
stock.partner = partner
stock.partner_sku = partner_sku
- stock.price_excl_tax = D(price_excl_tax)
+ stock.price = D(price)
stock.num_in_stock = num_in_stock
stock.save()
diff --git a/src/oscar/apps/partner/migrations/0006_auto_20200724_0909.py b/src/oscar/apps/partner/migrations/0006_auto_20200724_0909.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/partner/migrations/0006_auto_20200724_0909.py
@@ -0,0 +1,31 @@
+# Generated by Django 2.2.10 on 2020-07-24 08:09
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('partner', '0005_auto_20181115_1953'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='stockrecord',
+ name='cost_price',
+ ),
+ migrations.RemoveField(
+ model_name='stockrecord',
+ name='price_retail',
+ ),
+ migrations.AlterField(
+ model_name='stockrecord',
+ name='price_excl_tax',
+ field=models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True, verbose_name='Price'),
+ ),
+ migrations.RenameField(
+ model_name='stockrecord',
+ old_name='price_excl_tax',
+ new_name='price',
+ ),
+ ]
diff --git a/src/oscar/apps/partner/strategy.py b/src/oscar/apps/partner/strategy.py
--- a/src/oscar/apps/partner/strategy.py
+++ b/src/oscar/apps/partner/strategy.py
@@ -229,17 +229,17 @@ def parent_availability_policy(self, product, children_stock):
class NoTax(object):
"""
Pricing policy mixin for use with the ``Structured`` base strategy.
- This mixin specifies zero tax and uses the ``price_excl_tax`` from the
+ This mixin specifies zero tax and uses the ``price`` from the
stockrecord.
"""
def pricing_policy(self, product, stockrecord):
# Check stockrecord has the appropriate data
- if not stockrecord or stockrecord.price_excl_tax is None:
+ if not stockrecord or stockrecord.price is None:
return UnavailablePrice()
return FixedPrice(
currency=stockrecord.price_currency,
- excl_tax=stockrecord.price_excl_tax,
+ excl_tax=stockrecord.price,
tax=D('0.00'))
def parent_pricing_policy(self, product, children_stock):
@@ -250,7 +250,7 @@ def parent_pricing_policy(self, product, children_stock):
stockrecord = stockrecords[0]
return FixedPrice(
currency=stockrecord.price_currency,
- excl_tax=stockrecord.price_excl_tax,
+ excl_tax=stockrecord.price,
tax=D('0.00'))
@@ -265,14 +265,14 @@ class FixedRateTax(object):
exponent = D('0.01') # Default to two decimal places
def pricing_policy(self, product, stockrecord):
- if not stockrecord or stockrecord.price_excl_tax is None:
+ if not stockrecord or stockrecord.price is None:
return UnavailablePrice()
rate = self.get_rate(product, stockrecord)
exponent = self.get_exponent(stockrecord)
- tax = (stockrecord.price_excl_tax * rate).quantize(exponent)
+ tax = (stockrecord.price * rate).quantize(exponent)
return TaxInclusiveFixedPrice(
currency=stockrecord.price_currency,
- excl_tax=stockrecord.price_excl_tax,
+ excl_tax=stockrecord.price,
tax=tax)
def parent_pricing_policy(self, product, children_stock):
@@ -284,11 +284,11 @@ def parent_pricing_policy(self, product, children_stock):
stockrecord = stockrecords[0]
rate = self.get_rate(product, stockrecord)
exponent = self.get_exponent(stockrecord)
- tax = (stockrecord.price_excl_tax * rate).quantize(exponent)
+ tax = (stockrecord.price * rate).quantize(exponent)
return FixedPrice(
currency=stockrecord.price_currency,
- excl_tax=stockrecord.price_excl_tax,
+ excl_tax=stockrecord.price,
tax=tax)
def get_rate(self, product, stockrecord):
@@ -318,11 +318,11 @@ class DeferredTax(object):
"""
def pricing_policy(self, product, stockrecord):
- if not stockrecord or stockrecord.price_excl_tax is None:
+ if not stockrecord or stockrecord.price is None:
return UnavailablePrice()
return FixedPrice(
currency=stockrecord.price_currency,
- excl_tax=stockrecord.price_excl_tax)
+ excl_tax=stockrecord.price)
def parent_pricing_policy(self, product, children_stock):
stockrecords = [x[1] for x in children_stock if x[1] is not None]
@@ -334,7 +334,7 @@ def parent_pricing_policy(self, product, children_stock):
return FixedPrice(
currency=stockrecord.price_currency,
- excl_tax=stockrecord.price_excl_tax)
+ excl_tax=stockrecord.price)
# Example strategy composed of above mixins. For real projects, it's likely
| diff --git a/src/oscar/test/basket.py b/src/oscar/test/basket.py
--- a/src/oscar/test/basket.py
+++ b/src/oscar/test/basket.py
@@ -23,7 +23,7 @@ def add_product(basket, price=None, quantity=1, product=None):
record = product.stockrecords.all()[0]
else:
record = factories.create_stockrecord(
- product=product, price_excl_tax=price,
+ product=product, price=price,
num_in_stock=quantity + 1)
basket.add_product(record.product, quantity)
diff --git a/src/oscar/test/factories/__init__.py b/src/oscar/test/factories/__init__.py
--- a/src/oscar/test/factories/__init__.py
+++ b/src/oscar/test/factories/__init__.py
@@ -49,7 +49,7 @@
ConditionalOffer = get_model('offer', 'ConditionalOffer')
-def create_stockrecord(product=None, price_excl_tax=None, partner_sku=None,
+def create_stockrecord(product=None, price=None, partner_sku=None,
num_in_stock=None, partner_name=None,
currency=settings.OSCAR_DEFAULT_CURRENCY,
partner_users=None):
@@ -59,21 +59,21 @@ def create_stockrecord(product=None, price_excl_tax=None, partner_sku=None,
if partner_users:
for user in partner_users:
partner.users.add(user)
- if price_excl_tax is None:
- price_excl_tax = D('9.99')
+ if price is None:
+ price = D('9.99')
if partner_sku is None:
partner_sku = 'sku_%d_%d' % (product.id, random.randint(0, 10000))
return product.stockrecords.create(
partner=partner, partner_sku=partner_sku,
price_currency=currency,
- price_excl_tax=price_excl_tax, num_in_stock=num_in_stock)
+ price=price, num_in_stock=num_in_stock)
def create_purchase_info(record):
return PurchaseInfo(
price=FixedPrice(
record.price_currency,
- record.price_excl_tax,
+ record.price,
D('0.00') # Default to no tax
),
availability=StockRequired(
@@ -109,7 +109,7 @@ def create_product(upc=None, title="Dùmϻϒ title",
price, partner_sku, partner_name, num_in_stock, partner_users]
if any([field is not None for field in stockrecord_fields]):
create_stockrecord(
- product, price_excl_tax=price, num_in_stock=num_in_stock,
+ product, price=price, num_in_stock=num_in_stock,
partner_users=partner_users, partner_sku=partner_sku,
partner_name=partner_name)
return product
@@ -157,8 +157,7 @@ def create_order(number=None, basket=None, user=None, shipping_address=None,
basket = Basket.objects.create()
basket.strategy = Default()
product = create_product()
- create_stockrecord(
- product, num_in_stock=10, price_excl_tax=D('10.00'))
+ create_stockrecord(product, num_in_stock=10, price=D('10.00'))
basket.add_product(product)
if not basket.id:
basket.save()
diff --git a/src/oscar/test/factories/order.py b/src/oscar/test/factories/order.py
--- a/src/oscar/test/factories/order.py
+++ b/src/oscar/test/factories/order.py
@@ -100,24 +100,16 @@ class OrderLineFactory(factory.DjangoModelFactory):
lambda l: l.product.stockrecords.first())
quantity = 1
- line_price_incl_tax = factory.LazyAttribute(
- lambda obj: tax_add(obj.stockrecord.price_excl_tax) * obj.quantity)
- line_price_excl_tax = factory.LazyAttribute(
- lambda obj: obj.stockrecord.price_excl_tax * obj.quantity)
+ line_price_incl_tax = factory.LazyAttribute(lambda obj: tax_add(obj.stockrecord.price) * obj.quantity)
+ line_price_excl_tax = factory.LazyAttribute(lambda obj: obj.stockrecord.price * obj.quantity)
line_price_before_discounts_incl_tax = (
factory.SelfAttribute('.line_price_incl_tax'))
line_price_before_discounts_excl_tax = (
factory.SelfAttribute('.line_price_excl_tax'))
- unit_price_incl_tax = factory.LazyAttribute(
- lambda obj: tax_add(obj.stockrecord.price_excl_tax))
- unit_cost_price = factory.LazyAttribute(
- lambda obj: obj.stockrecord.cost_price)
- unit_price_excl_tax = factory.LazyAttribute(
- lambda obj: obj.stockrecord.price_excl_tax)
- unit_retail_price = factory.LazyAttribute(
- lambda obj: obj.stockrecord.price_retail)
+ unit_price_incl_tax = factory.LazyAttribute(lambda obj: tax_add(obj.stockrecord.price))
+ unit_price_excl_tax = factory.LazyAttribute(lambda obj: obj.stockrecord.price)
class Meta:
model = get_model('order', 'Line')
diff --git a/src/oscar/test/factories/partner.py b/src/oscar/test/factories/partner.py
--- a/src/oscar/test/factories/partner.py
+++ b/src/oscar/test/factories/partner.py
@@ -29,7 +29,7 @@ class StockRecordFactory(factory.DjangoModelFactory):
partner = factory.SubFactory(PartnerFactory)
partner_sku = factory.Sequence(lambda n: 'unit%d' % n)
price_currency = "GBP"
- price_excl_tax = D('9.99')
+ price = D('9.99')
num_in_stock = 100
class Meta:
diff --git a/tests/_site/apps/partner/migrations/0007_auto_20200724_0909.py b/tests/_site/apps/partner/migrations/0007_auto_20200724_0909.py
new file mode 100644
--- /dev/null
+++ b/tests/_site/apps/partner/migrations/0007_auto_20200724_0909.py
@@ -0,0 +1,31 @@
+# Generated by Django 2.2.10 on 2020-07-24 08:09
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('partner', '0006_auto_20190816_0910'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='stockrecord',
+ name='cost_price',
+ ),
+ migrations.RemoveField(
+ model_name='stockrecord',
+ name='price_retail',
+ ),
+ migrations.AlterField(
+ model_name='stockrecord',
+ name='price_excl_tax',
+ field=models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True, verbose_name='Price'),
+ ),
+ migrations.RenameField(
+ model_name='stockrecord',
+ old_name='price_excl_tax',
+ new_name='price',
+ ),
+ ]
diff --git a/tests/functional/checkout/__init__.py b/tests/functional/checkout/__init__.py
--- a/tests/functional/checkout/__init__.py
+++ b/tests/functional/checkout/__init__.py
@@ -17,14 +17,14 @@ def create_digital_product(self):
requires_shipping=False, track_stock=False)
product = factories.ProductFactory(product_class=product_class)
factories.StockRecordFactory(
- num_in_stock=None, price_excl_tax=D('12.00'), product=product)
+ num_in_stock=None, price=D('12.00'), product=product)
return product
def add_product_to_basket(self, product=None):
if product is None:
product = factories.ProductFactory()
factories.StockRecordFactory(
- num_in_stock=10, price_excl_tax=D('12.00'), product=product)
+ num_in_stock=10, price=D('12.00'), product=product)
detail_page = self.get(product.get_absolute_url())
form = detail_page.forms['add_to_basket_form']
form.submit()
diff --git a/tests/functional/dashboard/test_catalogue.py b/tests/functional/dashboard/test_catalogue.py
--- a/tests/functional/dashboard/test_catalogue.py
+++ b/tests/functional/dashboard/test_catalogue.py
@@ -127,7 +127,7 @@ def test_can_create_and_continue_editing_a_product(self):
form['stockrecords-0-partner'] = self.partner.id
form['stockrecords-0-partner_sku'] = '14'
form['stockrecords-0-num_in_stock'] = '555'
- form['stockrecords-0-price_excl_tax'] = '13.99'
+ form['stockrecords-0-price'] = '13.99'
page = form.submit(name='action', value='continue')
self.assertEqual(Product.objects.count(), 1)
diff --git a/tests/functional/test_basket.py b/tests/functional/test_basket.py
--- a/tests/functional/test_basket.py
+++ b/tests/functional/test_basket.py
@@ -64,7 +64,7 @@ def test_price_is_recorded(self):
basket = Basket.objects.get(id=basket_id)
line = basket.lines.get(product=self.product)
stockrecord = self.product.stockrecords.all()[0]
- self.assertEqual(stockrecord.price_excl_tax, line.price_excl_tax)
+ self.assertEqual(stockrecord.price, line.price_excl_tax)
class BasketSummaryViewTests(WebTestCase):
diff --git a/tests/integration/basket/test_models.py b/tests/integration/basket/test_models.py
--- a/tests/integration/basket/test_models.py
+++ b/tests/integration/basket/test_models.py
@@ -84,7 +84,7 @@ def test_line_tax_for_zero_tax_strategies(self):
product = factories.create_product()
# Tax for the default strategy will be 0
factories.create_stockrecord(
- product, price_excl_tax=D('75.00'), num_in_stock=10)
+ product, price=D('75.00'), num_in_stock=10)
basket.add(product, 1)
self.assertEqual(basket.lines.first().line_tax, D('0'))
@@ -95,7 +95,7 @@ class UnknownTaxStrategy(strategy.Default):
""" A test strategy where the tax is not known """
def pricing_policy(self, product, stockrecord):
- return prices.FixedPrice('GBP', stockrecord.price_excl_tax, tax=None)
+ return prices.FixedPrice('GBP', stockrecord.price, tax=None)
basket = Basket()
basket.strategy = UnknownTaxStrategy()
@@ -114,7 +114,7 @@ def setUp(self):
self.product = factories.create_product()
self.record = factories.create_stockrecord(
currency='GBP',
- product=self.product, price_excl_tax=D('10.00'))
+ product=self.product, price=D('10.00'))
self.purchase_info = factories.create_purchase_info(self.record)
self.basket.add(self.product)
@@ -136,7 +136,7 @@ def test_adding_negative_quantity(self):
def test_means_another_currency_product_cannot_be_added(self):
product = factories.create_product()
factories.create_stockrecord(
- currency='USD', product=product, price_excl_tax=D('20.00'))
+ currency='USD', product=product, price=D('20.00'))
with self.assertRaises(ValueError):
self.basket.add(product)
@@ -153,7 +153,7 @@ def setUp(self):
self.basket.strategy = strategy.Default()
self.product = factories.create_product()
self.record = factories.create_stockrecord(
- self.product, price_excl_tax=D('10.00'))
+ self.product, price=D('10.00'))
self.purchase_info = factories.create_purchase_info(self.record)
self.basket.add(self.product, 10)
@@ -171,21 +171,21 @@ def test_returns_correct_line_quantity_for_existing_product_and_stockrecord(self
def test_returns_zero_line_quantity_for_alternative_stockrecord(self):
record = factories.create_stockrecord(
- self.product, price_excl_tax=D('5.00'))
+ self.product, price=D('5.00'))
self.assertEqual(0, self.basket.line_quantity(
self.product, record))
def test_returns_zero_line_quantity_for_missing_product_and_stockrecord(self):
product = factories.create_product()
record = factories.create_stockrecord(
- product, price_excl_tax=D('5.00'))
+ product, price=D('5.00'))
self.assertEqual(0, self.basket.line_quantity(
product, record))
def test_returns_correct_quantity_for_existing_product_and_stockrecord_and_options(self):
product = factories.create_product()
record = factories.create_stockrecord(
- product, price_excl_tax=D('5.00'))
+ product, price=D('5.00'))
option = Option.objects.create(name="Message")
options = [{"option": option, "value": "2"}]
@@ -198,7 +198,7 @@ def test_returns_correct_quantity_for_existing_product_and_stockrecord_and_optio
def test_total_sums_product_totals(self):
product = factories.create_product()
factories.create_stockrecord(
- product, price_excl_tax=D('5.00'))
+ product, price=D('5.00'))
self.basket.add(product, 1)
self.assertEqual(self.basket.total_excl_tax, 105)
@@ -208,7 +208,7 @@ def test_totals_for_free_products(self):
# Add a zero-priced product to the basket
product = factories.create_product()
factories.create_stockrecord(
- product, price_excl_tax=D('0.00'), num_in_stock=10)
+ product, price=D('0.00'), num_in_stock=10)
basket.add(product, 1)
self.assertEqual(basket.lines.count(), 1)
@@ -218,7 +218,7 @@ def test_totals_for_free_products(self):
def test_basket_prices_calculation_for_unavailable_pricing(self):
new_product = factories.create_product()
factories.create_stockrecord(
- new_product, price_excl_tax=D('5.00'))
+ new_product, price=D('5.00'))
self.basket.add(new_product, 1)
class UnavailableProductStrategy(strategy.Default):
@@ -288,7 +288,7 @@ class TestMergingTwoBaskets(TestCase):
def setUp(self):
self.product = factories.create_product()
self.record = factories.create_stockrecord(
- self.product, price_excl_tax=D('10.00'))
+ self.product, price=D('10.00'))
self.purchase_info = factories.create_purchase_info(self.record)
self.main_basket = Basket()
diff --git a/tests/integration/partner/test_availability_mixin.py b/tests/integration/partner/test_availability_mixin.py
--- a/tests/integration/partner/test_availability_mixin.py
+++ b/tests/integration/partner/test_availability_mixin.py
@@ -12,7 +12,7 @@ def setUp(self):
self.mixin = strategy.StockRequired()
self.product = mock.Mock()
self.stockrecord = mock.Mock()
- self.stockrecord.price_excl_tax = D('12.00')
+ self.stockrecord.price = D('12.00')
def test_returns_unavailable_without_stockrecord(self):
policy = self.mixin.availability_policy(
diff --git a/tests/integration/partner/test_import.py b/tests/integration/partner/test_import.py
--- a/tests/integration/partner/test_import.py
+++ b/tests/integration/partner/test_import.py
@@ -96,7 +96,7 @@ def test_null_fields_are_skipped(self):
def test_price_is_imported(self):
stockrecord = self.product.stockrecords.all()[0]
- self.assertEqual(D('10.32'), stockrecord.price_excl_tax)
+ self.assertEqual(D('10.32'), stockrecord.price)
def test_num_in_stock_is_imported(self):
stockrecord = self.product.stockrecords.all()[0]
diff --git a/tests/integration/partner/test_models.py b/tests/integration/partner/test_models.py
--- a/tests/integration/partner/test_models.py
+++ b/tests/integration/partner/test_models.py
@@ -15,10 +15,10 @@ class TestStockRecord(TestCase):
def setUp(self):
self.product = factories.create_product()
self.stockrecord = factories.create_stockrecord(
- self.product, price_excl_tax=D('10.00'), num_in_stock=10)
+ self.product, price=D('10.00'), num_in_stock=10)
def test_get_price_excl_tax_returns_correct_value(self):
- self.assertEqual(D('10.00'), self.stockrecord.price_excl_tax)
+ self.assertEqual(D('10.00'), self.stockrecord.price)
def test_net_stock_level_with_no_allocation(self):
self.assertEqual(10, self.stockrecord.net_stock_level)
@@ -64,7 +64,7 @@ def setUp(self):
def test_allocate_does_nothing(self):
product = factories.ProductFactory(product_class=self.product_class)
stockrecord = factories.create_stockrecord(
- product, price_excl_tax=D('10.00'), num_in_stock=10)
+ product, price=D('10.00'), num_in_stock=10)
self.assertFalse(stockrecord.can_track_allocations)
stockrecord.allocate(5)
@@ -76,7 +76,7 @@ def test_allocate_does_nothing_for_child_product(self):
child_product = factories.ProductFactory(
parent=parent_product, product_class=None, structure='child')
stockrecord = factories.create_stockrecord(
- child_product, price_excl_tax=D('10.00'), num_in_stock=10)
+ child_product, price=D('10.00'), num_in_stock=10)
self.assertFalse(stockrecord.can_track_allocations)
stockrecord.allocate(5)
diff --git a/tests/integration/partner/test_strategy.py b/tests/integration/partner/test_strategy.py
--- a/tests/integration/partner/test_strategy.py
+++ b/tests/integration/partner/test_strategy.py
@@ -53,7 +53,7 @@ def test_availability_does_not_require_price(self):
# The availability policy should be independent of price.
product_class = factories.ProductClassFactory(track_stock=False)
product = factories.ProductFactory(product_class=product_class, stockrecords=[])
- factories.StockRecordFactory(price_excl_tax=None, product=product)
+ factories.StockRecordFactory(price=None, product=product)
info = self.strategy.fetch_for_product(product)
self.assertTrue(info.availability.is_available_to_buy)
@@ -123,7 +123,7 @@ class TestFixedRateTax(TestCase):
def test_pricing_policy_unavailable_if_no_price_excl_tax(self):
product = factories.ProductFactory(stockrecords=[])
- factories.StockRecordFactory(price_excl_tax=None, product=product)
+ factories.StockRecordFactory(price=None, product=product)
info = strategy.UK().fetch_for_product(product)
self.assertFalse(info.price.exists)
@@ -132,6 +132,6 @@ class TestDeferredTax(TestCase):
def test_pricing_policy_unavailable_if_no_price_excl_tax(self):
product = factories.ProductFactory(stockrecords=[])
- factories.StockRecordFactory(price_excl_tax=None, product=product)
+ factories.StockRecordFactory(price=None, product=product)
info = strategy.US().fetch_for_product(product)
self.assertFalse(info.price.exists)
diff --git a/tests/integration/partner/test_tax_mixin.py b/tests/integration/partner/test_tax_mixin.py
--- a/tests/integration/partner/test_tax_mixin.py
+++ b/tests/integration/partner/test_tax_mixin.py
@@ -12,7 +12,7 @@ def setUp(self):
self.mixin = strategy.NoTax()
self.product = mock.Mock()
self.stockrecord = mock.Mock()
- self.stockrecord.price_excl_tax = D('12.00')
+ self.stockrecord.price = D('12.00')
def test_returns_no_prices_without_stockrecord(self):
policy = self.mixin.pricing_policy(
@@ -37,7 +37,7 @@ def setUp(self):
self.mixin.rate = D('0.10')
self.product = mock.Mock()
self.stockrecord = mock.Mock()
- self.stockrecord.price_excl_tax = D('12.00')
+ self.stockrecord.price = D('12.00')
def test_returns_no_prices_without_stockrecord(self):
policy = self.mixin.pricing_policy(
@@ -47,7 +47,7 @@ def test_returns_no_prices_without_stockrecord(self):
def test_returns_correct_tax(self):
policy = self.mixin.pricing_policy(
self.product, self.stockrecord)
- expected_tax = self.stockrecord.price_excl_tax * self.mixin.get_rate(
+ expected_tax = self.stockrecord.price * self.mixin.get_rate(
self.product, self.stockrecord)
self.assertEqual(expected_tax, policy.tax)
diff --git a/tests/integration/shipping/test_model_method.py b/tests/integration/shipping/test_model_method.py
--- a/tests/integration/shipping/test_model_method.py
+++ b/tests/integration/shipping/test_model_method.py
@@ -69,7 +69,7 @@ def test_free_shipping_with_empty_basket(self):
self.assertEqual(D('0.00'), charge.incl_tax)
def test_free_shipping_with_nonempty_basket(self):
- record = factories.create_stockrecord(price_excl_tax=D('5.00'))
+ record = factories.create_stockrecord(price=D('5.00'))
self.basket.add_product(record.product)
charge = self.method.calculate(self.basket)
self.assertEqual(D('0.00'), charge.incl_tax)
@@ -83,7 +83,7 @@ def setUp(self):
self.basket = factories.create_basket(empty=True)
def test_basket_below_threshold(self):
- record = factories.create_stockrecord(price_excl_tax=D('5.00'))
+ record = factories.create_stockrecord(price=D('5.00'))
self.basket.add_product(record.product)
charge = self.method.calculate(self.basket)
@@ -91,7 +91,7 @@ def test_basket_below_threshold(self):
self.assertEqual(D('10.00'), charge.incl_tax)
def test_basket_on_threshold(self):
- record = factories.create_stockrecord(price_excl_tax=D('5.00'))
+ record = factories.create_stockrecord(price=D('5.00'))
self.basket.add_product(record.product, quantity=4)
charge = self.method.calculate(self.basket)
@@ -99,7 +99,7 @@ def test_basket_on_threshold(self):
self.assertEqual(D('0.00'), charge.incl_tax)
def test_basket_above_threshold(self):
- record = factories.create_stockrecord(price_excl_tax=D('5.00'))
+ record = factories.create_stockrecord(price=D('5.00'))
self.basket.add_product(record.product, quantity=8)
charge = self.method.calculate(self.basket)
diff --git a/tests/unit/fixtures/catalogue.json b/tests/unit/fixtures/catalogue.json
--- a/tests/unit/fixtures/catalogue.json
+++ b/tests/unit/fixtures/catalogue.json
@@ -159,9 +159,7 @@
"partner": 1,
"partner_sku": "henk",
"price_currency": "EUR",
- "price_excl_tax": "400.00",
- "price_retail": "500.00",
- "cost_price": "300.00",
+ "price": "400.00",
"num_in_stock": 23,
"num_allocated": null,
"low_stock_threshold": null,
@@ -177,9 +175,7 @@
"partner": 1,
"partner_sku": "asdasd",
"price_currency": "EUR",
- "price_excl_tax": "23.00",
- "price_retail": "0.05",
- "cost_price": null,
+ "price": "23.00",
"num_in_stock": null,
"num_allocated": null,
"low_stock_threshold": null,
diff --git a/tests/unit/fixtures/productattributes.json b/tests/unit/fixtures/productattributes.json
--- a/tests/unit/fixtures/productattributes.json
+++ b/tests/unit/fixtures/productattributes.json
@@ -803,9 +803,7 @@
"partner": 1,
"partner_sku": "henk",
"price_currency": "EUR",
- "price_excl_tax": "400.00",
- "price_retail": "500.00",
- "cost_price": "300.00",
+ "price": "400.00",
"num_in_stock": 23,
"num_allocated": null,
"low_stock_threshold": null,
@@ -821,9 +819,7 @@
"partner": 1,
"partner_sku": "asdasd",
"price_currency": "EUR",
- "price_excl_tax": "23.00",
- "price_retail": "0.05",
- "cost_price": null,
+ "price": "23.00",
"num_in_stock": null,
"num_allocated": null,
"low_stock_threshold": null,
@@ -839,9 +835,7 @@
"partner": 1,
"partner_sku": "err56",
"price_currency": "EUR",
- "price_excl_tax": "234.00",
- "price_retail": "123.00",
- "cost_price": null,
+ "price": "234.00",
"num_in_stock": 345,
"num_allocated": null,
"low_stock_threshold": 12,
@@ -857,9 +851,7 @@
"partner": 1,
"partner_sku": "23478",
"price_currency": "EUR",
- "price_excl_tax": "12.00",
- "price_retail": "11.00",
- "cost_price": null,
+ "price": "12.00",
"num_in_stock": 34,
"num_allocated": null,
"low_stock_threshold": 8,
| StockRecord: rename price_excl_tax
The docstring for `price_excl_tax` already explains what it truly is: the base price for tax calculations. I've had two projects where we knew the tax-inclusive price, and only calculated the price excl tax. I'd argue that a stock record is merely a record of a base price, and only the pricing policy gives it any meaning in regards to tax, so the field name should reflect that.
I realize that the field is probably used directly more often than it should (instead of through pricing strategies), so we need a good idea about being friendly as far as backwards-compatibility is concerned.
| Yeah I agree! :+1: All projects i've worked on communicate the tax-inclusive price and we need to calculate the excl price. This is required for prices like 19.99 where going from excl to incl results in 20.00 which isn't what the client wants :-)
If that's the case, we should probably ship some sample strategies to show how to work with this as well. Note to self: when doing this, also look at potential off-by-one bugs when calculating line and basket totals.
This issue actually contained two issues, renaming a field and deleting two. As I found more candidates for deletion, I moved that part of this issue into https://github.com/django-oscar/django-oscar/issues/1968
@maikhoepfel @mvantellingen how about renaming into `base_price`? What about backward compatibility?
I think you should be careful with renaming this field. Having the price excluding tax and calculate the price including tax yourselves make more sense than the other way around (Especially if you have international shops).
However, I agree that the StockRecord should supply a base price and that the pricing policy gives a meaning to it, so it should not named like this.
I would say to deprecate the `price_excl_tax` field for the next release (1.2?) and rename it to a more sane name in the release after?
@sasha0 Backwards compatibility could be tricky. Initially, I thought we could define a `price_excl_tax` property, but that would only handle a few cases. Basically any code that references `price_excl_tax` using the ORM would break.
After research and observation, I came to conclusion it does make sense to rename `price_excl_tax` into `price` but as @john-parton mentioned before, there's no chance to make this change backwards compatible which drastically reduces motivation to apply this change.
I also totally agree with @maerteijn that we'd firstly deprecate this field and rename in the next major release (2.0).
nice to hear that, I had to disable the tax calculation because of it. The disadvantages I see is to deal with multiple countries with different taxes and in b2b pricing.
I may would propose the ability to limit stockrecords to countries. | "2019-05-07T04:51:13Z" | 2.1 | [] | [
"tests/functional/checkout/test_customer_checkout.py::TestIndexView::test_redirects_customers_to_shipping_address_view",
"tests/functional/checkout/test_customer_checkout.py::TestIndexView::test_redirects_customers_with_empty_basket",
"tests/functional/checkout/test_customer_checkout.py::TestIndexView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_can_select_an_existing_shipping_address",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_only_shipping_addresses_are_shown",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_submitting_valid_form_adds_data_to_session",
"tests/functional/checkout/test_customer_checkout.py::TestUserAddressUpdateView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestUserAddressUpdateView::test_submitting_valid_form_modifies_user_address",
"tests/functional/checkout/test_customer_checkout.py::TestShippingMethodView::test_redirects_when_only_one_shipping_method",
"tests/functional/checkout/test_customer_checkout.py::TestShippingMethodView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestDeleteUserAddressView::test_can_delete_a_user_address_from_shipping_address_page",
"tests/functional/checkout/test_customer_checkout.py::TestDeleteUserAddressView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestPreviewView::test_allows_order_to_be_placed",
"tests/functional/checkout/test_customer_checkout.py::TestPlacingAnOrderUsingAVoucher::test_records_use",
"tests/functional/checkout/test_customer_checkout.py::TestPlacingAnOrderUsingAnOffer::test_records_use",
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::test_superusers_can_force_an_order",
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::test_users_cannot_force_an_other_custumer_order",
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::tests_custumers_can_reach_the_thank_you_page",
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::tests_gets_a_404_when_there_is_no_order",
"tests/functional/dashboard/test_catalogue.py::TestCatalogueViews::test_exist",
"tests/functional/dashboard/test_catalogue.py::TestCatalogueViews::test_is_public",
"tests/functional/dashboard/test_catalogue.py::TestCatalogueViews::test_upc_filter",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_create_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_create_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_create_product_with_required_attributes",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_delete_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_delete_a_parent_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_delete_a_standalone_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_list_her_products",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_update_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_cant_create_child_product_for_invalid_parents",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_create_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_create_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_create_product_with_required_attributes",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_delete_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_delete_a_parent_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_delete_a_standalone_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_list_her_products",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_update_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_cant_create_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_cant_create_child_product_for_invalid_parents",
"tests/functional/test_basket.py::TestBasketMerging::test_cookie_basket_has_status_set",
"tests/functional/test_basket.py::TestBasketMerging::test_lines_are_moved_across",
"tests/functional/test_basket.py::TestBasketMerging::test_merge_line_takes_max_quantity",
"tests/functional/test_basket.py::AnonAddToBasketViewTests::test_cookie_is_created",
"tests/functional/test_basket.py::AnonAddToBasketViewTests::test_price_is_recorded",
"tests/functional/test_basket.py::BasketSummaryViewTests::test_basket_in_context",
"tests/functional/test_basket.py::BasketSummaryViewTests::test_basket_is_empty",
"tests/functional/test_basket.py::BasketSummaryViewTests::test_order_total_in_context",
"tests/functional/test_basket.py::BasketSummaryViewTests::test_shipping_method_in_context",
"tests/functional/test_basket.py::BasketSummaryViewTests::test_view_does_not_error",
"tests/functional/test_basket.py::BasketThresholdTest::test_adding_more_than_threshold_raises",
"tests/functional/test_basket.py::BasketReportTests::test_open_report_doesnt_error",
"tests/functional/test_basket.py::BasketReportTests::test_submitted_report_doesnt_error",
"tests/functional/test_basket.py::SavedBasketTests::test_moving_from_saved_basket",
"tests/functional/test_basket.py::SavedBasketTests::test_moving_from_saved_basket_more_than_stocklevel_raises",
"tests/functional/test_basket.py::SavedBasketTests::test_moving_to_saved_basket_creates_new",
"tests/functional/test_basket.py::SavedBasketTests::test_moving_to_saved_basket_updates_existing",
"tests/functional/test_basket.py::BasketFormSetTests::test_deleting_invalid_line_with_other_invalid_line",
"tests/functional/test_basket.py::BasketFormSetTests::test_deleting_invalid_line_with_other_valid_line",
"tests/functional/test_basket.py::BasketFormSetTests::test_deleting_valid_line_with_other_invalid_line",
"tests/functional/test_basket.py::BasketFormSetTests::test_deleting_valid_line_with_other_valid_line",
"tests/functional/test_basket.py::BasketFormSetTests::test_formset_with_removed_line",
"tests/functional/test_basket.py::BasketFormSetTests::test_invalid_formset_with_removed_line",
"tests/integration/basket/test_models.py::TestANewBasket::test_can_be_edited",
"tests/integration/basket/test_models.py::TestANewBasket::test_doesnt_contain_vouchers",
"tests/integration/basket/test_models.py::TestANewBasket::test_has_no_applied_offers",
"tests/integration/basket/test_models.py::TestANewBasket::test_has_zero_items",
"tests/integration/basket/test_models.py::TestANewBasket::test_has_zero_lines",
"tests/integration/basket/test_models.py::TestANewBasket::test_is_empty",
"tests/integration/basket/test_models.py::TestANewBasket::test_is_not_submitted",
"tests/integration/basket/test_models.py::TestBasketLine::test_basket_lines_queryset_is_ordered",
"tests/integration/basket/test_models.py::TestBasketLine::test_create_line_reference",
"tests/integration/basket/test_models.py::TestBasketLine::test_description",
"tests/integration/basket/test_models.py::TestBasketLine::test_description_with_attributes",
"tests/integration/basket/test_models.py::TestBasketLine::test_line_tax_for_unknown_tax_strategies",
"tests/integration/basket/test_models.py::TestBasketLine::test_line_tax_for_zero_tax_strategies",
"tests/integration/basket/test_models.py::TestAddingAProductToABasket::test_adding_negative_quantity",
"tests/integration/basket/test_models.py::TestAddingAProductToABasket::test_cannot_add_a_product_without_price",
"tests/integration/basket/test_models.py::TestAddingAProductToABasket::test_creates_a_line",
"tests/integration/basket/test_models.py::TestAddingAProductToABasket::test_means_another_currency_product_cannot_be_added",
"tests/integration/basket/test_models.py::TestAddingAProductToABasket::test_sets_line_prices",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_basket_prices_calculation_for_unavailable_pricing",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_can_be_flushed",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_is_quantity_allowed",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_max_allowed_quantity",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_returns_correct_line_quantity_for_existing_product_and_stockrecord",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_returns_correct_product_quantity",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_returns_correct_quantity_for_existing_product_and_stockrecord_and_options",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_returns_zero_line_quantity_for_alternative_stockrecord",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_returns_zero_line_quantity_for_missing_product_and_stockrecord",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_total_sums_product_totals",
"tests/integration/basket/test_models.py::TestANonEmptyBasket::test_totals_for_free_products",
"tests/integration/basket/test_models.py::TestMergingTwoBaskets::test_changes_status_of_merge_basket",
"tests/integration/basket/test_models.py::TestMergingTwoBaskets::test_doesnt_sum_quantities",
"tests/integration/basket/test_models.py::TestASubmittedBasket::test_can_be_edited",
"tests/integration/basket/test_models.py::TestASubmittedBasket::test_has_correct_status",
"tests/integration/basket/test_models.py::TestMergingAVoucherBasket::test_transfers_vouchers_to_new_basket",
"tests/integration/partner/test_availability_mixin.py::TestStockRequiredMixin::test_returns_available_when_product_class_doesnt_track_stock",
"tests/integration/partner/test_availability_mixin.py::TestStockRequiredMixin::test_returns_stockrequired_when_product_class_does_track_stock",
"tests/integration/partner/test_availability_mixin.py::TestStockRequiredMixin::test_returns_unavailable_without_stockrecord",
"tests/integration/partner/test_import.py::CommandEdgeCasesTest::test_importing_nonexistant_file_raises_exception",
"tests/integration/partner/test_import.py::CommandEdgeCasesTest::test_sending_directory_as_file_raises_exception",
"tests/integration/partner/test_import.py::CommandEdgeCasesTest::test_sending_no_file_argument_raises_exception",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_all_rows_are_imported",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_class_is_created",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_item_is_created",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_null_fields_are_skipped",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_num_in_stock_is_imported",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_only_one_class_is_created",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_partner_is_created",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_price_is_imported",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_stockrecord_is_created",
"tests/integration/partner/test_import.py::ImportSmokeTest::test_title_is_imported",
"tests/integration/partner/test_import.py::ImportSemicolonDelimitedFileTest::test_import",
"tests/integration/partner/test_import.py::ImportWithFlushTest::test_items_are_flushed_by_importer",
"tests/integration/partner/test_models.py::TestStockRecord::test_allocated_does_not_alter_num_in_stock",
"tests/integration/partner/test_models.py::TestStockRecord::test_allocation_handles_null_value",
"tests/integration/partner/test_models.py::TestStockRecord::test_cancelling_allocation",
"tests/integration/partner/test_models.py::TestStockRecord::test_cancelling_allocation_ignores_too_big_allocations",
"tests/integration/partner/test_models.py::TestStockRecord::test_consuming_allocation",
"tests/integration/partner/test_models.py::TestStockRecord::test_get_price_excl_tax_returns_correct_value",
"tests/integration/partner/test_models.py::TestStockRecord::test_net_stock_level_with_allocation",
"tests/integration/partner/test_models.py::TestStockRecord::test_net_stock_level_with_no_allocation",
"tests/integration/partner/test_models.py::TestStockRecordNoStockTrack::test_allocate_does_nothing",
"tests/integration/partner/test_models.py::TestStockRecordNoStockTrack::test_allocate_does_nothing_for_child_product",
"tests/integration/partner/test_models.py::TestPartnerAddress::test_can_get_primary_address",
"tests/integration/partner/test_models.py::TestPartnerAddress::test_fails_on_two_addresses",
"tests/integration/partner/test_strategy.py::TestDefaultStrategy::test_availability_does_not_require_price",
"tests/integration/partner/test_strategy.py::TestDefaultStrategy::test_free_product_is_available_to_buy",
"tests/integration/partner/test_strategy.py::TestDefaultStrategy::test_line_method_is_same_as_product_one",
"tests/integration/partner/test_strategy.py::TestDefaultStrategy::test_no_stockrecords",
"tests/integration/partner/test_strategy.py::TestDefaultStrategy::test_one_stockrecord",
"tests/integration/partner/test_strategy.py::TestDefaultStrategy::test_product_which_doesnt_track_stock",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWhoseVariantsHaveNoStockRecords::test_specifies_correct_availability_code",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWhoseVariantsHaveNoStockRecords::test_specifies_product_has_no_price",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWhoseVariantsHaveNoStockRecords::test_specifies_product_is_unavailable",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWithInStockVariant::test_specifies_correct_availability_code",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWithInStockVariant::test_specifies_product_has_correct_price",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWithInStockVariant::test_specifies_product_is_available",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWithOutOfStockVariant::test_specifies_correct_availability_code",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWithOutOfStockVariant::test_specifies_product_has_correct_price",
"tests/integration/partner/test_strategy.py::TestDefaultStrategyForParentProductWithOutOfStockVariant::test_specifies_product_is_unavailable",
"tests/integration/partner/test_strategy.py::TestFixedRateTax::test_pricing_policy_unavailable_if_no_price_excl_tax",
"tests/integration/partner/test_strategy.py::TestDeferredTax::test_pricing_policy_unavailable_if_no_price_excl_tax",
"tests/integration/partner/test_tax_mixin.py::TestNoTaxMixin::test_doesnt_add_tax_to_net_price",
"tests/integration/partner/test_tax_mixin.py::TestNoTaxMixin::test_returns_no_prices_without_stockrecord",
"tests/integration/partner/test_tax_mixin.py::TestNoTaxMixin::test_returns_zero_tax",
"tests/integration/partner/test_tax_mixin.py::TestFixedRateTaxMixin::test_adds_tax_to_net_price",
"tests/integration/partner/test_tax_mixin.py::TestFixedRateTaxMixin::test_returns_correct_tax",
"tests/integration/partner/test_tax_mixin.py::TestFixedRateTaxMixin::test_returns_no_prices_without_stockrecord",
"tests/integration/shipping/test_model_method.py::TestOrderAndItemCharges::test_multi_item_basket",
"tests/integration/shipping/test_model_method.py::TestOrderAndItemCharges::test_returns_order_level_charge_for_empty_basket",
"tests/integration/shipping/test_model_method.py::TestOrderAndItemCharges::test_single_item_basket",
"tests/integration/shipping/test_model_method.py::TestOrderAndItemCharges::test_single_item_basket_that_doesnt_require_shipping",
"tests/integration/shipping/test_model_method.py::TestOrderAndItemCharges::test_tax_is_known",
"tests/integration/shipping/test_model_method.py::ZeroFreeThresholdTest::test_free_shipping_with_empty_basket",
"tests/integration/shipping/test_model_method.py::ZeroFreeThresholdTest::test_free_shipping_with_nonempty_basket",
"tests/integration/shipping/test_model_method.py::TestNonZeroFreeThreshold::test_basket_above_threshold",
"tests/integration/shipping/test_model_method.py::TestNonZeroFreeThreshold::test_basket_below_threshold",
"tests/integration/shipping/test_model_method.py::TestNonZeroFreeThreshold::test_basket_on_threshold",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_for_smoke_with_basket_charge",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_get_band_for_higher_weight",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_get_band_for_lower_weight",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_get_band_for_matching_weight",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_get_band_for_series_of_bands",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_get_band_for_series_of_bands_from_different_methods",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_get_band_for_zero_weight",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_get_charge_when_weight_is_divided_by_top_band_upper_limit_without_remainder",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_overflow_shipping_cost_scenario_handled_correctly",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_simple_shipping_cost_scenario_handled_correctly",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_weight_from_for_multiple_bands",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_weight_from_for_single_band",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_weight_to_is_upper_bound",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_zero_charge_discount",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_zero_charge_with_shipping_discount",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_zero_weight_baskets_can_have_a_charge",
"tests/integration/shipping/test_model_method.py::WeightBasedMethodTests::test_zero_weight_baskets_can_have_no_charge"
] | [] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,485 | django-oscar__django-oscar-3485 | [
"2652"
] | b6b42aeb0fd31ea17a9ec1caca901bb53c8437fa | diff --git a/src/oscar/apps/basket/abstract_models.py b/src/oscar/apps/basket/abstract_models.py
--- a/src/oscar/apps/basket/abstract_models.py
+++ b/src/oscar/apps/basket/abstract_models.py
@@ -714,7 +714,7 @@ def consume(self, quantity, offer=None):
Consumed items are no longer available to be used in offers.
"""
- self.consumer.consume(quantity, offer=offer)
+ return self.consumer.consume(quantity, offer=offer)
def get_price_breakdown(self):
"""
diff --git a/src/oscar/apps/basket/utils.py b/src/oscar/apps/basket/utils.py
--- a/src/oscar/apps/basket/utils.py
+++ b/src/oscar/apps/basket/utils.py
@@ -82,18 +82,19 @@ class LineOfferConsumer(object):
"""
def __init__(self, line):
- self.__line = line
- self.__offers = dict()
- self.__affected_quantity = 0
- self.__consumptions = defaultdict(int)
+ self._line = line
+ self._offers = dict()
+ self._affected_quantity = 0
+ self._consumptions = defaultdict(int)
- # private
- def __cache(self, offer):
- self.__offers[offer.pk] = offer
+ def _cache(self, offer):
+ self._offers[offer.pk] = offer
- def __update_affected_quantity(self, quantity):
- available = int(self.__line.quantity - self.__affected_quantity)
- self.__affected_quantity += min(available, quantity)
+ def _update_affected_quantity(self, quantity):
+ available = int(self._line.quantity - self._affected_quantity)
+ num_consumed = min(available, quantity)
+ self._affected_quantity += num_consumed
+ return num_consumed
# public
def consume(self, quantity: int, offer=None):
@@ -103,16 +104,22 @@ def consume(self, quantity: int, offer=None):
:param int quantity: the number of items on the line affected
:param offer: the offer to mark the line
:type offer: ConditionalOffer or None
+ :return: the number of items actually consumed
+ :rtype: int
if offer is None, the specified quantity of items on this
basket line is consumed for *any* offer, else only for the
specified offer.
"""
- self.__update_affected_quantity(quantity)
if offer:
- self.__cache(offer)
+ self._cache(offer)
available = self.available(offer)
- self.__consumptions[offer.pk] += min(available, quantity)
+
+ num_consumed = self._update_affected_quantity(quantity)
+ if offer:
+ num_consumed = min(available, quantity)
+ self._consumptions[offer.pk] += num_consumed
+ return num_consumed
def consumed(self, offer=None):
"""
@@ -129,12 +136,12 @@ def consumed(self, offer=None):
"""
if not offer:
- return self.__affected_quantity
- return int(self.__consumptions[offer.pk])
+ return self._affected_quantity
+ return int(self._consumptions[offer.pk])
@property
def consumers(self):
- return [x for x in self.__offers.values() if self.consumed(x)]
+ return [x for x in self._offers.values() if self.consumed(x)]
def available(self, offer=None) -> int:
"""
@@ -145,7 +152,7 @@ def available(self, offer=None) -> int:
:return: the number of items available for offer
:rtype: int
"""
- max_affected_items = self.__line.quantity
+ max_affected_items = self._line.quantity
if offer and isinstance(offer, ConditionalOffer):
@@ -160,6 +167,12 @@ def available(self, offer=None) -> int:
if offer.exclusive and len(applied):
return 0
+ # check for applied offers allowing restricted combinations
+ for x in applied:
+ check = offer.combinations.count() or x.combinations.count()
+ if check and offer not in x.combined_offers:
+ return 0
+
# respect max_affected_items
if offer.benefit.max_affected_items:
max_affected_items = min(offer.benefit.max_affected_items, max_affected_items)
diff --git a/src/oscar/apps/dashboard/offers/forms.py b/src/oscar/apps/dashboard/offers/forms.py
--- a/src/oscar/apps/dashboard/offers/forms.py
+++ b/src/oscar/apps/dashboard/offers/forms.py
@@ -36,7 +36,7 @@ class Meta:
fields = ('start_datetime', 'end_datetime',
'max_basket_applications', 'max_user_applications',
'max_global_applications', 'max_discount',
- 'priority', 'exclusive')
+ 'priority', 'exclusive', 'combinations')
def clean(self):
cleaned_data = super().clean()
@@ -45,8 +45,35 @@ def clean(self):
if start and end and end < start:
raise forms.ValidationError(_(
"The end date must be after the start date"))
+ exclusive = cleaned_data['exclusive']
+ combinations = cleaned_data['combinations']
+ if exclusive and combinations:
+ raise forms.ValidationError(_('Exclusive offers cannot be combined'))
return cleaned_data
+ def save(self, *args, **kwargs):
+ """Store the offer combinations.
+
+ Also, and make sure the combinations are stored on the combine-able
+ offers as well.
+ """
+ instance = super().save(*args, **kwargs)
+ if instance.id:
+ instance.combinations.clear()
+ for offer in self.cleaned_data['combinations']:
+ if offer != instance:
+ instance.combinations.add(offer)
+
+ combined_offers = instance.combined_offers
+ for offer in combined_offers:
+ if offer == instance:
+ continue
+ for otheroffer in combined_offers:
+ if offer == otheroffer:
+ continue
+ offer.combinations.add(otheroffer)
+ return instance
+
class ConditionForm(forms.ModelForm):
custom_condition = forms.ChoiceField(
diff --git a/src/oscar/apps/dashboard/offers/views.py b/src/oscar/apps/dashboard/offers/views.py
--- a/src/oscar/apps/dashboard/offers/views.py
+++ b/src/oscar/apps/dashboard/offers/views.py
@@ -111,9 +111,15 @@ def _store_form_kwargs(self, form):
# Adjust kwargs to avoid trying to save the range instance
form_data = form.cleaned_data.copy()
- range = form_data.get('range', None)
- if range is not None:
- form_data['range'] = range.id
+ product_range = form_data.get('range')
+ if product_range is not None:
+ form_data['range'] = product_range.id
+
+ combinations = form_data.get('combinations')
+ if combinations is not None:
+ form_data['combination_ids'] = [x.id for x in combinations]
+ del form_data['combinations']
+
form_kwargs = {'data': form_data}
json_data = json.dumps(form_kwargs, cls=DjangoJSONEncoder)
@@ -136,7 +142,17 @@ def _store_object(self, form):
# We don't store the object instance as that is not JSON serialisable.
# Instead, we save an alternative form
instance = form.save(commit=False)
- json_qs = serializers.serialize('json', [instance])
+ fields = form.fields.keys()
+ safe_fields = ['custom_benefit', 'custom_condition']
+ # remove fields that do not exist (yet) on the uncommitted instance, i.e. m2m fields
+ # unless they are 'virtual' fields as listed in 'safe_fields'
+ cleanfields = {x: hasattr(instance, x) for x in fields}
+ cleanfields.update({x: True for x in fields if x in safe_fields})
+ cleanfields = [
+ x[0] for x in cleanfields.items() if x[1]
+ ]
+
+ json_qs = serializers.serialize('json', [instance], fields=tuple(cleanfields))
session_data[self._key(is_object=True)] = json_qs
self.request.session.save()
@@ -152,10 +168,10 @@ def _fetch_object(self, step_name, request=None):
return deserialised_obj[0].object
def _fetch_session_offer(self):
- """
- Return the offer instance loaded with the data stored in the
- session. When updating an offer, the updated fields are used with the
- existing offer data.
+ """Return the offer instance loaded with the data stored in the session.
+
+ When updating an offer, the updated fields are used with the existing
+ offer data.
"""
offer = self._fetch_object('metadata')
if offer is None and self.update:
diff --git a/src/oscar/apps/offer/abstract_models.py b/src/oscar/apps/offer/abstract_models.py
--- a/src/oscar/apps/offer/abstract_models.py
+++ b/src/oscar/apps/offer/abstract_models.py
@@ -119,6 +119,13 @@ class AbstractConditionalOffer(models.Model):
help_text=_("Exclusive offers cannot be combined on the same items"),
default=True
)
+ combinations = models.ManyToManyField(
+ 'offer.ConditionalOffer',
+ help_text=_('Select other non-exclusive offers that this offer can be combined with on the same items'),
+ related_name='in_combination',
+ limit_choices_to={'exclusive': False},
+ blank=True,
+ )
# We track a status variable so it's easier to load offers that are
# 'available' in some sense.
@@ -443,6 +450,14 @@ def products(self):
return queryset.filter(is_discountable=True).exclude(
structure=Product.CHILD)
+ @cached_property
+ def combined_offers(self):
+ return self.__class__.objects.filter(
+ models.Q(pk=self.pk)
+ | models.Q(pk__in=self.combinations.values_list("pk", flat=True))
+ | models.Q(pk__in=self.in_combination.values_list("pk", flat=True))
+ ).distinct()
+
class AbstractBenefit(BaseOfferMixin, models.Model):
range = models.ForeignKey(
diff --git a/src/oscar/apps/offer/conditions.py b/src/oscar/apps/offer/conditions.py
--- a/src/oscar/apps/offer/conditions.py
+++ b/src/oscar/apps/offer/conditions.py
@@ -92,13 +92,9 @@ def consume_items(self, offer, basket, affected_lines):
if to_consume == 0:
return
- for __, line in self.get_applicable_lines(offer, basket,
- most_expensive_first=True):
- quantity_to_consume = min(
- line.quantity_without_offer_discount(offer), to_consume
- )
- line.consume(quantity_to_consume, offer=offer)
- to_consume -= quantity_to_consume
+ for __, line in self.get_applicable_lines(offer, basket, most_expensive_first=True):
+ num_consumed = line.consume(to_consume, offer=offer)
+ to_consume -= num_consumed
if to_consume == 0:
break
diff --git a/src/oscar/apps/offer/migrations/0010_conditionaloffer_combinations.py b/src/oscar/apps/offer/migrations/0010_conditionaloffer_combinations.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/offer/migrations/0010_conditionaloffer_combinations.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.0.9 on 2020-08-28 09:03
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('offer', '0009_auto_20200801_0817'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='conditionaloffer',
+ name='combinations',
+ field=models.ManyToManyField(blank=True, help_text='Select other non-exclusive offers that this offer can be combined with on the same items', limit_choices_to={'exclusive': False}, related_name='in_combination', to='offer.ConditionalOffer'),
+ ),
+ ]
| diff --git a/tests/integration/basket/test_utils.py b/tests/integration/basket/test_utils.py
--- a/tests/integration/basket/test_utils.py
+++ b/tests/integration/basket/test_utils.py
@@ -118,7 +118,7 @@ def test_consume(self, filled_basket):
line.consume(99)
assert line.quantity_with_discount == 10
- def test_consumed_with_exclusive_offer(self, filled_basket):
+ def test_consumed_with_exclusive_offer_1(self, filled_basket):
offer1 = ConditionalOfferFactory(name='offer1')
offer2 = ConditionalOfferFactory(name='offer2')
offer3 = ConditionalOfferFactory(name='offer3')
@@ -132,7 +132,9 @@ def test_consumed_with_exclusive_offer(self, filled_basket):
line1, line2 = list(filled_basket.all_lines())
+ # exclusive offer consumes one item on line1
line1.consumer.consume(1, offer1)
+
# offer1 is exclusive so that blocks other offers
assert line1.is_available_for_offer_discount(offer2) is False
@@ -153,9 +155,126 @@ def test_consumed_with_exclusive_offer(self, filled_basket):
# but still room for offer3!
assert line2.is_available_for_offer_discount(offer3) is True
+ def test_consumed_with_exclusive_offer_2(self, filled_basket):
+ offer1 = ConditionalOfferFactory(name='offer1')
+ offer2 = ConditionalOfferFactory(name='offer2')
+ offer3 = ConditionalOfferFactory(name='offer3')
+ offer1.exclusive = True
+ offer2.exclusive = False
+ offer3.exclusive = False
+
+ for line in filled_basket.all_lines():
+ assert line.consumer.consumed(offer1) == 0
+ assert line.consumer.consumed(offer2) == 0
+
+ line1, line2 = list(filled_basket.all_lines())
+
+ # exclusive offer consumes one item on line1
+ line1.consumer.consume(1, offer1)
+ remaining1 = line1.quantity - 1
+
+ assert line1.quantity_with_offer_discount(offer1) == 1
+ assert line1.quantity_with_offer_discount(offer2) == 0
+ assert line1.quantity_with_offer_discount(offer3) == 0
+
+ assert line1.quantity_without_offer_discount(offer1) == remaining1
+ assert line1.quantity_without_offer_discount(offer2) == 0
+ assert line1.quantity_without_offer_discount(offer3) == 0
+
+ # exclusive offer consumes all items on line1
+ line1.consumer.consume(remaining1, offer1)
+ assert line1.quantity_with_offer_discount(offer1) == line1.quantity
+ assert line1.quantity_with_offer_discount(offer2) == 0
+ assert line1.quantity_with_offer_discount(offer3) == 0
+
+ assert line1.quantity_without_offer_discount(offer1) == 0
+ assert line1.quantity_without_offer_discount(offer2) == 0
+ assert line1.quantity_without_offer_discount(offer3) == 0
+
+ # non-exclusive offer consumes one item on line2
+ line2.consumer.consume(1, offer2)
+ remaining2 = line2.quantity - 1
+
+ assert line2.quantity_with_offer_discount(offer1) == 0
+ assert line2.quantity_with_offer_discount(offer2) == 1
+ assert line2.quantity_with_offer_discount(offer3) == 0
+
+ assert line2.quantity_without_offer_discount(offer1) == 0
+ assert line2.quantity_without_offer_discount(offer2) == remaining2
+ assert line2.quantity_without_offer_discount(offer3) == line2.quantity
+
+ # non-exclusive offer consumes all items on line2
+ line2.consumer.consume(remaining2, offer2)
+
+ assert line2.quantity_with_offer_discount(offer1) == 0
+ assert line2.quantity_with_offer_discount(offer2) == line2.quantity
+ assert line2.quantity_with_offer_discount(offer3) == 0
+
+ assert line2.quantity_without_offer_discount(offer1) == 0
+ assert line2.quantity_without_offer_discount(offer2) == 0
+ assert line2.quantity_without_offer_discount(offer3) == line2.quantity
+
def test_consumed_by_application(self, filled_basket, single_offer):
basket = filled_basket
Applicator().apply(basket)
assert len(basket.offer_applications.offer_discounts) == 1
-
assert [x.consumer.consumed() for x in basket.all_lines()] == [1, 0]
+
+ def test_consumed_with_combined_offer(self, filled_basket):
+ offer1 = ConditionalOfferFactory(name='offer1')
+ offer2 = ConditionalOfferFactory(name='offer2')
+ offer3 = ConditionalOfferFactory(name='offer3')
+ offer4 = ConditionalOfferFactory(name='offer4')
+ offer1.exclusive = True
+ offer2.exclusive = False
+ offer3.exclusive = False
+ offer4.exclusive = False
+ offer2.combinations.add(offer3)
+ assert offer3 in offer2.combined_offers
+ assert offer2 in offer3.combined_offers
+
+ for line in filled_basket.all_lines():
+ assert line.consumer.consumed(offer1) == 0
+ assert line.consumer.consumed(offer2) == 0
+ assert line.consumer.consumed(offer3) == 0
+
+ line1 = filled_basket.all_lines()[0]
+
+ # combinable offer consumes one item of line1
+ line1.consumer.consume(1, offer2)
+ remaining1 = line1.quantity - 1
+
+ assert line1.quantity_with_offer_discount(offer1) == 0
+ assert line1.quantity_with_offer_discount(offer2) == 1
+ assert line1.quantity_with_offer_discount(offer3) == 0
+ assert line1.quantity_with_offer_discount(offer4) == 0
+
+ assert line1.quantity_without_offer_discount(offer1) == 0
+ assert line1.quantity_without_offer_discount(offer2) == remaining1
+ assert line1.quantity_without_offer_discount(offer3) == line1.quantity
+ assert line1.quantity_without_offer_discount(offer4) == 0
+
+ # combinable offer consumes one item of line1
+ line1.consumer.consume(1, offer3)
+ assert line1.quantity_with_offer_discount(offer1) == 0
+ assert line1.quantity_with_offer_discount(offer2) == 1
+ assert line1.quantity_with_offer_discount(offer3) == 1
+ assert line1.quantity_with_offer_discount(offer4) == 0
+
+ assert line1.quantity_without_offer_discount(offer1) == 0
+ assert line1.quantity_without_offer_discount(offer2) == remaining1
+ assert line1.quantity_without_offer_discount(offer3) == remaining1
+ assert line1.quantity_without_offer_discount(offer4) == 0
+
+ # combinable offer consumes all items of line1
+ line1.consumer.consume(remaining1, offer2)
+
+ assert line1.quantity_with_offer_discount(offer1) == 0
+ assert line1.quantity_with_offer_discount(offer2) == line1.quantity
+ assert line1.quantity_with_offer_discount(offer3) == 1
+ assert line1.quantity_with_offer_discount(offer4) == 0
+
+ assert line1.quantity_without_offer_discount(offer1) == 0
+ assert line1.quantity_without_offer_discount(offer2) == 0
+ assert line1.quantity_without_offer_discount(offer3) == remaining1
+ assert line1.quantity_without_offer_discount(offer4) == 0
| Offer Tracking for Stacked Offers
I was testing out the stacked offer tracking that will be included in v1.6 and came across what may be a problem. It looks like the `LineOfferConsumer` class might be tracking the applied offers incorrectly.
As an example, in the basket app when `AbstractLine.consume()` runs it should mark a line as consumed using `LineOfferConsumer.consume()` and passing the applicable offer. I think it should be storing the offer that consumed the items regardless of if the offer was exclusive or not. However, if the offer is exclusive it doesn't store the offer that consumed the line items.
This is for a test basket with an offer that should be applied to all three items in the line:
```python
class Line(AbstractLine):
def consume(self, quantity, offer=None):
super(Line, self).consume(quantity, offer)
print "offer------------------------->", offer
print "exclusive--------------------->", offer.exclusive
print "has_discount------------------>", self.has_discount
print "quantity_with_discount-------->", self.quantity_with_discount
print "has_offer_discount------------>", self.has_offer_discount(offer)
print "quantity_with_offer_discount-->", self.quantity_with_offer_discount(offer)
```
Output:
```
offer-------------------------> Discount 123456
exclusive---------------------> True
has_discount------------------> True
quantity_with_discount--------> 3
has_offer_discount------------> False
quantity_with_offer_discount--> 0
```
If the offer is set to non-exclusive then the behavior is as expected:
```
offer-------------------------> Discount 123456
exclusive---------------------> False
has_discount------------------> True
quantity_with_discount--------> 3
has_offer_discount------------> True
quantity_with_offer_discount--> 3
```
I don't actually need stacked offers per se, I just need to know what offer was applied to the line as a whole. Maybe this is stored somewhere else when a whole line is consumed by the same offer?
| I'll take a look at this asap.
The LineOfferConsumer interface could do with more extensive tests. | "2020-08-28T09:12:41Z" | 2.1 | [] | [
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_combined_offer"
] | [
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_no_offer",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_available_with_offer",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_offer",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consume",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_exclusive_offer_1",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_exclusive_offer_2",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_by_application"
] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,684 | django-oscar__django-oscar-3684 | [
"3662"
] | 04cd6a4fc750db9310147d96776f06fe289269bf | diff --git a/src/oscar/apps/dashboard/offers/views.py b/src/oscar/apps/dashboard/offers/views.py
--- a/src/oscar/apps/dashboard/offers/views.py
+++ b/src/oscar/apps/dashboard/offers/views.py
@@ -140,11 +140,9 @@ def _store_form_kwargs(self, form):
session_data[self._key()] = json_data
self.request.session.save()
- def _fetch_form_kwargs(self, step_name=None):
- if not step_name:
- step_name = self.step_name
+ def _fetch_form_kwargs(self):
session_data = self.request.session.setdefault(self.wizard_name, {})
- json_data = session_data.get(self._key(step_name), None)
+ json_data = session_data.get(self._key(self.step_name), None)
if json_data:
return json.loads(json_data)
@@ -156,15 +154,8 @@ def _store_object(self, form):
# We don't store the object instance as that is not JSON serialisable.
# Instead, we save an alternative form
instance = form.save(commit=False)
- fields = form.fields.keys()
- safe_fields = ['custom_benefit', 'custom_condition']
# remove fields that do not exist (yet) on the uncommitted instance, i.e. m2m fields
- # unless they are 'virtual' fields as listed in 'safe_fields'
- cleanfields = {x: hasattr(instance, x) for x in fields}
- cleanfields.update({x: True for x in fields if x in safe_fields})
- cleanfields = [
- x[0] for x in cleanfields.items() if x[1]
- ]
+ cleanfields = [field.name for field in instance._meta.local_fields]
json_qs = serializers.serialize('json', [instance], fields=tuple(cleanfields))
| diff --git a/tests/integration/dashboard/test_offer_views.py b/tests/integration/dashboard/test_offer_views.py
--- a/tests/integration/dashboard/test_offer_views.py
+++ b/tests/integration/dashboard/test_offer_views.py
@@ -1,17 +1,26 @@
+import json
+
import pytest
from django.contrib.messages import get_messages
+from django.test import TestCase
from django.urls import reverse
+from freezegun import freeze_time
from oscar.apps.dashboard.offers import views as offer_views
from oscar.apps.dashboard.ranges import views as range_views
+from oscar.apps.offer.custom import create_benefit, create_condition
from oscar.core.loading import get_model
from oscar.test.factories.catalogue import ProductFactory
from oscar.test.factories.offer import ConditionalOfferFactory, RangeFactory
from oscar.test.factories.voucher import VoucherFactory
+from tests._site.model_tests_app.models import (
+ CustomBenefitModel, CustomConditionModel)
from tests.fixtures import RequestFactory
Range = get_model('offer', 'Range')
ConditionalOffer = get_model('offer', 'ConditionalOffer')
+Benefit = get_model('offer', 'Benefit')
+Condition = get_model('offer', 'Condition')
@pytest.fixture
@@ -106,3 +115,619 @@ def test_range_product_list_view(self, rf, range_with_products):
assert response.context_data['paginator']
assert response.context_data['page_obj']
assert response.status_code == 200
+
+
+class TestCreateOfferWizardStepView(TestCase):
+
+ def setUp(self):
+ range_ = RangeFactory()
+
+ self.metadata_form_kwargs_session_data = {
+ 'data': {
+ 'name': 'Test offer',
+ 'slug': '',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.SITE,
+ 'exclusive': True,
+ 'status': ConditionalOffer.OPEN,
+ 'condition': None,
+ 'benefit': None,
+ 'priority': 0,
+ 'start_datetime': None,
+ 'end_datetime': None,
+ 'max_global_applications': None,
+ 'max_user_applications': None,
+ 'max_basket_applications': None,
+ 'max_discount': None,
+ 'total_discount': '0.00',
+ 'num_applications': 0,
+ 'num_orders': 0,
+ 'redirect_url': '',
+ 'date_created': None,
+ },
+ }
+ self.metadata_obj_session_data = [{
+ 'model': 'offer.conditionaloffer',
+ 'pk': None,
+ 'fields': {
+ 'name': 'Test offer',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.SITE,
+ },
+ }]
+ self.benefit_form_kwargs_session_data = {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Benefit.PERCENTAGE,
+ 'value': '10',
+ 'max_affected_items': None,
+ 'custom_benefit': '',
+ },
+ }
+ self.benefit_obj_session_data = [{
+ 'model': 'offer.benefit',
+ 'pk': None,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Benefit.PERCENTAGE,
+ 'value': '10',
+ 'max_affected_items': None,
+ 'proxy_class': None,
+ },
+ }]
+ self.condition_form_kwargs_session_data = {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Condition.COUNT,
+ 'value': '10',
+ 'custom_condition': '',
+ },
+ }
+ self.condition_obj_session_data = [{
+ 'model': 'offer.condition',
+ 'pk': None,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Condition.COUNT,
+ 'value': '10',
+ 'proxy_class': None,
+ },
+ }]
+
+ def test_offer_meta_data_view(self):
+ request = RequestFactory().post('/', data={
+ 'name': 'Test offer',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.SITE,
+ })
+ response = offer_views.OfferMetaDataView.as_view()(request)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-benefit'))
+ self.assertJSONEqual(request.session['offer_wizard']['metadata'], {
+ 'data': {
+ 'name': 'Test offer',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.SITE,
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard']['metadata_obj'], [{
+ 'model': 'offer.conditionaloffer',
+ 'pk': None,
+ 'fields': {
+ 'name': 'Test offer',
+ 'slug': '',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.SITE,
+ 'exclusive': True,
+ 'status': ConditionalOffer.OPEN,
+ 'condition': None,
+ 'benefit': None,
+ 'priority': 0,
+ 'start_datetime': None,
+ 'end_datetime': None,
+ 'max_global_applications': None,
+ 'max_user_applications': None,
+ 'max_basket_applications': None,
+ 'max_discount': None,
+ 'total_discount': '0.00',
+ 'num_applications': 0,
+ 'num_orders': 0,
+ 'redirect_url': '',
+ 'date_created': None,
+ },
+ }])
+
+ def test_offer_benefit_view_with_built_in_benefit_type(self):
+ range_ = RangeFactory()
+
+ request = RequestFactory().post('/', data={
+ 'range': range_.pk,
+ 'type': Benefit.PERCENTAGE,
+ 'value': 10,
+ })
+ request.session['offer_wizard'] = {
+ 'metadata': json.dumps(self.metadata_form_kwargs_session_data),
+ 'metadata_obj': json.dumps(self.metadata_obj_session_data),
+ }
+ response = offer_views.OfferBenefitView.as_view()(request)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-condition'))
+ self.assertJSONEqual(request.session['offer_wizard']['metadata'], self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['metadata_obj'], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['benefit'], {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Benefit.PERCENTAGE,
+ 'value': '10',
+ 'max_affected_items': None,
+ 'custom_benefit': '',
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard']['benefit_obj'], [{
+ 'model': 'offer.benefit',
+ 'pk': None,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Benefit.PERCENTAGE,
+ 'value': '10',
+ 'max_affected_items': None,
+ 'proxy_class': None,
+ },
+ }])
+
+ def test_offer_benefit_view_with_custom_benefit_type(self):
+ benefit = create_benefit(CustomBenefitModel)
+
+ request = RequestFactory().post('/', data={
+ 'custom_benefit': benefit.pk,
+ })
+ request.session['offer_wizard'] = {
+ 'metadata': json.dumps(self.metadata_form_kwargs_session_data),
+ 'metadata_obj': json.dumps(self.metadata_obj_session_data),
+ }
+ response = offer_views.OfferBenefitView.as_view()(request)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-condition'))
+ self.assertJSONEqual(request.session['offer_wizard']['metadata'], self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['metadata_obj'], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['benefit'], {
+ 'data': {
+ 'range': None,
+ 'type': '',
+ 'value': None,
+ 'max_affected_items': None,
+ 'custom_benefit': str(benefit.pk),
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard']['benefit_obj'], [{
+ 'model': 'offer.benefit',
+ 'pk': benefit.pk,
+ 'fields': {
+ 'range': None,
+ 'type': '',
+ 'value': None,
+ 'max_affected_items': None,
+ 'proxy_class': benefit.proxy_class,
+ }
+ }])
+
+ def test_offer_condition_view_with_built_in_condition_type(self):
+ range_ = RangeFactory()
+
+ request = RequestFactory().post('/', data={
+ 'range': range_.pk,
+ 'type': Condition.COUNT,
+ 'value': 10,
+ })
+ request.session['offer_wizard'] = {
+ 'metadata': json.dumps(self.metadata_form_kwargs_session_data),
+ 'metadata_obj': json.dumps(self.metadata_obj_session_data),
+ 'benefit': json.dumps(self.benefit_form_kwargs_session_data),
+ 'benefit_obj': json.dumps(self.benefit_obj_session_data),
+ }
+ response = offer_views.OfferConditionView.as_view()(request)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-restrictions'))
+ self.assertJSONEqual(request.session['offer_wizard']['metadata'], self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['metadata_obj'], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['benefit'], self.benefit_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['benefit_obj'], self.benefit_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['condition'], {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Condition.COUNT,
+ 'value': '10',
+ 'custom_condition': '',
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard']['condition_obj'], [{
+ 'model': 'offer.condition',
+ 'pk': None,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Condition.COUNT,
+ 'value': '10',
+ 'proxy_class': None,
+ },
+ }])
+
+ def test_offer_condition_view_with_custom_condition_type(self):
+ range_ = RangeFactory()
+ condition = create_condition(CustomConditionModel)
+
+ request = RequestFactory().post('/', data={
+ 'range': range_.pk,
+ 'custom_condition': condition.pk,
+ })
+ request.session['offer_wizard'] = {
+ 'metadata': json.dumps(self.metadata_form_kwargs_session_data),
+ 'metadata_obj': json.dumps(self.metadata_obj_session_data),
+ 'benefit': json.dumps(self.benefit_form_kwargs_session_data),
+ 'benefit_obj': json.dumps(self.benefit_obj_session_data),
+ }
+ response = offer_views.OfferConditionView.as_view()(request)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-restrictions'))
+ self.assertJSONEqual(request.session['offer_wizard']['metadata'], self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['metadata_obj'], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['benefit'], self.benefit_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['benefit_obj'], self.benefit_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard']['condition'], {
+ 'data': {
+ 'range': range_.pk,
+ 'type': '',
+ 'value': None,
+ 'custom_condition': str(condition.pk),
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard']['condition_obj'], [{
+ 'model': 'offer.condition',
+ 'pk': condition.pk,
+ 'fields': {
+ 'range': None,
+ 'type': '',
+ 'value': None,
+ 'proxy_class': condition.proxy_class,
+ }
+ }])
+
+ def test_offer_restrictions_view(self):
+ request = RequestFactory().post('/', data={
+ 'priority': 0,
+ })
+ request.session['offer_wizard'] = {
+ 'metadata': json.dumps(self.metadata_form_kwargs_session_data),
+ 'metadata_obj': json.dumps(self.metadata_obj_session_data),
+ 'benefit': json.dumps(self.benefit_form_kwargs_session_data),
+ 'benefit_obj': json.dumps(self.benefit_obj_session_data),
+ 'condition': json.dumps(self.condition_form_kwargs_session_data),
+ 'condition_obj': json.dumps(self.condition_obj_session_data),
+ }
+ response = offer_views.OfferRestrictionsView.as_view()(request)
+
+ offer = ConditionalOffer.objects.get()
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-detail', kwargs={'pk': offer.pk}))
+ self.assertEqual([(m.level_tag, str(m.message)) for m in get_messages(request)][0],
+ ('success', "Offer '%s' created!" % offer.name))
+ self.assertEqual(request.session['offer_wizard'], {})
+
+
+@freeze_time('2021-04-23 14:00:00')
+class TestUpdateOfferWizardStepView(TestCase):
+
+ def setUp(self):
+ self.offer = ConditionalOfferFactory()
+ self.metadata_form_kwargs_key = 'metadata%s' % self.offer.pk
+ self.metadata_obj_key = 'metadata%s_obj' % self.offer.pk
+ self.benefit_form_kwargs_key = 'benefit%s' % self.offer.pk
+ self.benefit_obj_key = 'benefit%s_obj' % self.offer.pk
+ self.condition_form_kwargs_key = 'condition%s' % self.offer.pk
+ self.condition_obj_key = 'condition%s_obj' % self.offer.pk
+ range_ = RangeFactory()
+
+ self.metadata_form_kwargs_session_data = {
+ 'data': {
+ 'name': 'Test offer',
+ 'slug': self.offer.slug,
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.VOUCHER,
+ 'exclusive': True,
+ 'status': ConditionalOffer.OPEN,
+ 'condition': self.offer.condition.pk,
+ 'benefit': self.offer.benefit.pk,
+ 'priority': 0,
+ 'start_datetime': None,
+ 'end_datetime': None,
+ 'max_global_applications': None,
+ 'max_user_applications': None,
+ 'max_basket_applications': None,
+ 'max_discount': None,
+ 'total_discount': '0.00',
+ 'num_applications': 0,
+ 'num_orders': 0,
+ 'redirect_url': '',
+ 'date_created': '2021-04-23T14:00:00Z',
+ },
+ }
+ self.metadata_obj_session_data = [{
+ 'model': 'offer.conditionaloffer',
+ 'pk': None,
+ 'fields': {
+ 'name': 'Test offer',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.VOUCHER,
+ },
+ }]
+ self.benefit_form_kwargs_session_data = {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Benefit.FIXED,
+ 'value': '2000',
+ 'max_affected_items': 2,
+ 'custom_benefit': '',
+ },
+ }
+ self.benefit_obj_session_data = [{
+ 'model': 'offer.benefit',
+ 'pk': None,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Benefit.FIXED,
+ 'value': '2000',
+ 'max_affected_items': 2,
+ 'proxy_class': '',
+ },
+ }]
+ self.condition_form_kwargs_session_data = {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Condition.VALUE,
+ 'value': '2000',
+ 'custom_condition': '',
+ },
+ }
+ self.condition_obj_session_data = [{
+ 'model': 'offer.condition',
+ 'pk': None,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Condition.VALUE,
+ 'value': '2000',
+ 'proxy_class': '',
+ },
+ }]
+
+ def test_offer_meta_data_view(self):
+ request = RequestFactory().post('/', data={
+ 'name': 'Test offer',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.VOUCHER,
+ })
+ response = offer_views.OfferMetaDataView.as_view(update=True)(request, pk=self.offer.pk)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-benefit', kwargs={'pk': self.offer.pk}))
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_form_kwargs_key], {
+ 'data': {
+ 'name': 'Test offer',
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.VOUCHER,
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_obj_key], [{
+ 'model': 'offer.conditionaloffer',
+ 'pk': self.offer.pk,
+ 'fields': {
+ 'name': 'Test offer',
+ 'slug': self.offer.slug,
+ 'description': 'Test description',
+ 'offer_type': ConditionalOffer.VOUCHER,
+ 'exclusive': True,
+ 'status': ConditionalOffer.OPEN,
+ 'condition': self.offer.condition.pk,
+ 'benefit': self.offer.benefit.pk,
+ 'priority': 0,
+ 'start_datetime': None,
+ 'end_datetime': None,
+ 'max_global_applications': None,
+ 'max_user_applications': None,
+ 'max_basket_applications': None,
+ 'max_discount': None,
+ 'total_discount': '0.00',
+ 'num_applications': 0,
+ 'num_orders': 0,
+ 'redirect_url': '',
+ 'date_created': '2021-04-23T14:00:00Z',
+ },
+ }])
+
+ def test_offer_benefit_view_with_built_in_benefit_type(self):
+ range_ = RangeFactory()
+
+ request = RequestFactory().post('/', data={
+ 'range': range_.pk,
+ 'type': Benefit.FIXED,
+ 'value': 2000,
+ })
+ request.session['offer_wizard'] = {
+ self.metadata_form_kwargs_key: json.dumps(self.metadata_form_kwargs_session_data),
+ self.metadata_obj_key: json.dumps(self.metadata_obj_session_data),
+ }
+ response = offer_views.OfferBenefitView.as_view(update=True)(request, pk=self.offer.pk)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-condition', kwargs={'pk': self.offer.pk}))
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_form_kwargs_key],
+ self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_obj_key], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_form_kwargs_key], {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Benefit.FIXED,
+ 'value': '2000',
+ 'max_affected_items': None,
+ 'custom_benefit': '',
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_obj_key], [{
+ 'model': 'offer.benefit',
+ 'pk': self.offer.benefit.pk,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Benefit.FIXED,
+ 'value': '2000',
+ 'max_affected_items': None,
+ 'proxy_class': '',
+ },
+ }])
+
+ def test_offer_benefit_view_with_custom_benefit_type(self):
+ benefit = create_benefit(CustomBenefitModel)
+
+ request = RequestFactory().post('/', data={
+ 'custom_benefit': benefit.pk,
+ })
+ request.session['offer_wizard'] = {
+ self.metadata_form_kwargs_key: json.dumps(self.metadata_form_kwargs_session_data),
+ self.metadata_obj_key: json.dumps(self.metadata_obj_session_data),
+ }
+ response = offer_views.OfferBenefitView.as_view(update=True)(request, pk=self.offer.pk)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-condition', kwargs={'pk': self.offer.pk}))
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_form_kwargs_key],
+ self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_obj_key], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_form_kwargs_key], {
+ 'data': {
+ 'range': None,
+ 'type': '',
+ 'value': None,
+ 'max_affected_items': None,
+ 'custom_benefit': str(benefit.pk),
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_obj_key], [{
+ 'model': 'offer.benefit',
+ 'pk': benefit.pk,
+ 'fields': {
+ 'range': None,
+ 'type': '',
+ 'value': None,
+ 'max_affected_items': None,
+ 'proxy_class': benefit.proxy_class,
+ }
+ }])
+
+ def test_offer_condition_view_with_built_in_condition_type(self):
+ range_ = RangeFactory()
+
+ request = RequestFactory().post('/', data={
+ 'range': range_.pk,
+ 'type': Condition.VALUE,
+ 'value': 2000,
+ })
+ request.session['offer_wizard'] = {
+ self.metadata_form_kwargs_key: json.dumps(self.metadata_form_kwargs_session_data),
+ self.metadata_obj_key: json.dumps(self.metadata_obj_session_data),
+ self.benefit_form_kwargs_key: json.dumps(self.benefit_form_kwargs_session_data),
+ self.benefit_obj_key: json.dumps(self.benefit_obj_session_data),
+ }
+ response = offer_views.OfferConditionView.as_view(update=True)(request, pk=self.offer.pk)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-restrictions', kwargs={'pk': self.offer.pk}))
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_form_kwargs_key],
+ self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_obj_key], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_form_kwargs_key],
+ self.benefit_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_obj_key], self.benefit_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.condition_form_kwargs_key], {
+ 'data': {
+ 'range': range_.pk,
+ 'type': Condition.VALUE,
+ 'value': '2000',
+ 'custom_condition': '',
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard'][self.condition_obj_key], [{
+ 'model': 'offer.condition',
+ 'pk': self.offer.condition.pk,
+ 'fields': {
+ 'range': range_.pk,
+ 'type': Condition.VALUE,
+ 'value': '2000',
+ 'proxy_class': '',
+ },
+ }])
+
+ def test_offer_condition_view_with_custom_condition_type(self):
+ range_ = RangeFactory()
+ condition = create_condition(CustomConditionModel)
+
+ request = RequestFactory().post('/', data={
+ 'range': range_.pk,
+ 'custom_condition': condition.pk,
+ })
+ request.session['offer_wizard'] = {
+ self.metadata_form_kwargs_key: json.dumps(self.metadata_form_kwargs_session_data),
+ self.metadata_obj_key: json.dumps(self.metadata_obj_session_data),
+ self.benefit_form_kwargs_key: json.dumps(self.benefit_form_kwargs_session_data),
+ self.benefit_obj_key: json.dumps(self.benefit_obj_session_data),
+ }
+ response = offer_views.OfferConditionView.as_view(update=True)(request, pk=self.offer.pk)
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-restrictions', kwargs={'pk': self.offer.pk}))
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_form_kwargs_key],
+ self.metadata_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.metadata_obj_key], self.metadata_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_form_kwargs_key],
+ self.benefit_form_kwargs_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.benefit_obj_key], self.benefit_obj_session_data)
+ self.assertJSONEqual(request.session['offer_wizard'][self.condition_form_kwargs_key], {
+ 'data': {
+ 'range': range_.pk,
+ 'type': '',
+ 'value': None,
+ 'custom_condition': str(condition.pk),
+ },
+ })
+ self.assertJSONEqual(request.session['offer_wizard'][self.condition_obj_key], [{
+ 'model': 'offer.condition',
+ 'pk': condition.pk,
+ 'fields': {
+ 'range': None,
+ 'type': '',
+ 'value': None,
+ 'proxy_class': condition.proxy_class,
+ }
+ }])
+
+ def test_offer_restrictions_view(self):
+ request = RequestFactory().post('/', data={
+ 'priority': 0,
+ })
+ request.session['offer_wizard'] = {
+ self.metadata_form_kwargs_key: json.dumps(self.metadata_form_kwargs_session_data),
+ self.metadata_obj_key: json.dumps(self.metadata_obj_session_data),
+ self.benefit_form_kwargs_key: json.dumps(self.benefit_form_kwargs_session_data),
+ self.benefit_obj_key: json.dumps(self.benefit_obj_session_data),
+ self.condition_form_kwargs_key: json.dumps(self.condition_form_kwargs_session_data),
+ self.condition_obj_key: json.dumps(self.condition_obj_session_data),
+ }
+ response = offer_views.OfferRestrictionsView.as_view(update=True)(request, pk=self.offer.pk)
+
+ self.offer.refresh_from_db()
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.url, reverse('dashboard:offer-detail', kwargs={'pk': self.offer.pk}))
+ self.assertEqual([(m.level_tag, str(m.message)) for m in get_messages(request)][0],
+ ('success', "Offer '%s' updated" % self.offer.name))
+ self.assertEqual(request.session['offer_wizard'], {})
| Benefit.proxy_class and Condition.proxy_class fields gets overridden if a new offer with a custom condition and benefit is created in the dashboard
I created a custom offer condition and a custom offer benefit according to the documentation (https://django-oscar.readthedocs.io/en/3.0.2/howto/how_to_create_a_custom_condition.html). After the benefit and condition is populated with the create_condition and create_benefit command I wanted to add a new offer with the custom condition and benefit. When I save the new offer in the dashboard both `proxy_class` fields are empty and I get a `Unrecognised condition type ()` error. If I then manually update the fields again, everything works fine.
### Technical details
* Python version: Python 3.8.2
* Django version: Django==2.2.17
* Oscar version: django-oscar==3.0
| @jwayodi is it possible to fix this in #3632? To reproduce on the sandbox:
1. Start creating an offer and choose the custom incentive (changes customer's name) instead of defining one.
2. Proceed through the other steps and you'll get an error at the final step.
This happens only on offer creation so the issue is with what is passed through the session during that flow. | "2021-03-16T06:13:01Z" | 3.0 | [] | [
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_benefit_view_with_built_in_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_benefit_view_with_custom_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_condition_view_with_built_in_condition_type",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_condition_view_with_custom_condition_type",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_meta_data_view",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_benefit_view_with_built_in_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_benefit_view_with_custom_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_condition_view_with_built_in_condition_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_condition_view_with_custom_condition_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_meta_data_view"
] | [
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_range_list_view",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_list_view",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_delete_view_for_voucher_offer_without_vouchers",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_delete_view_for_voucher_offer_with_vouchers",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_range_product_list_view",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_restrictions_view",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_restrictions_view"
] | 04cd6a4fc750db9310147d96776f06fe289269bf |
django-oscar/django-oscar | 3,497 | django-oscar__django-oscar-3497 | [
"3258"
] | 3e377f42c6835c982daaa9f9d020de510462d7c9 | diff --git a/src/oscar/apps/catalogue/abstract_models.py b/src/oscar/apps/catalogue/abstract_models.py
--- a/src/oscar/apps/catalogue/abstract_models.py
+++ b/src/oscar/apps/catalogue/abstract_models.py
@@ -15,7 +15,7 @@
from django.db.models.fields import Field
from django.db.models.lookups import StartsWith
from django.urls import reverse
-from django.utils.functional import cached_property
+from django.utils.functional import SimpleLazyObject, cached_property
from django.utils.html import strip_tags
from django.utils.safestring import mark_safe
from django.utils.translation import get_language
@@ -435,7 +435,7 @@ class Meta:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.attr = ProductAttributesContainer(product=self)
+ self.attr = SimpleLazyObject(lambda: ProductAttributesContainer(product=self))
def __str__(self):
if self.title:
diff --git a/src/oscar/apps/catalogue/product_attributes.py b/src/oscar/apps/catalogue/product_attributes.py
--- a/src/oscar/apps/catalogue/product_attributes.py
+++ b/src/oscar/apps/catalogue/product_attributes.py
@@ -2,7 +2,7 @@
from django.utils.translation import gettext_lazy as _
-class ProductAttributesContainer(object):
+class ProductAttributesContainer:
"""
Stolen liberally from django-eav, but simplified to be product-specific
@@ -13,25 +13,16 @@ class ProductAttributesContainer(object):
def __setstate__(self, state):
self.__dict__ = state
- self.initialised = False
def __init__(self, product):
self.product = product
- self.initialised = False
-
- def initiate_attributes(self):
values = self.get_values().select_related('attribute')
for v in values:
setattr(self, v.attribute.code, v.value)
- self.initialised = True
def __getattr__(self, name):
- if not name.startswith('_') and not self.initialised:
- self.initiate_attributes()
- return getattr(self, name)
raise AttributeError(
- _("%(obj)s has no attribute named '%(attr)s'") % {
- 'obj': self.product.get_product_class(), 'attr': name})
+ _("%(obj)s has no attribute named '%(attr)s'") % {'obj': self.product.get_product_class(), 'attr': name})
def validate_attributes(self):
for attribute in self.get_all_attributes():
diff --git a/src/oscar/apps/dashboard/catalogue/forms.py b/src/oscar/apps/dashboard/catalogue/forms.py
--- a/src/oscar/apps/dashboard/catalogue/forms.py
+++ b/src/oscar/apps/dashboard/catalogue/forms.py
@@ -286,7 +286,6 @@ def _post_clean(self):
Set attributes before ModelForm calls the product's clean method
(which it does in _post_clean), which in turn validates attributes.
"""
- self.instance.attr.initiate_attributes()
for attribute in self.instance.attr.get_all_attributes():
field_name = 'attr_%s' % attribute.code
# An empty text field won't show up in cleaned_data.
| diff --git a/tests/integration/catalogue/test_attributes.py b/tests/integration/catalogue/test_attributes.py
--- a/tests/integration/catalogue/test_attributes.py
+++ b/tests/integration/catalogue/test_attributes.py
@@ -4,9 +4,33 @@
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
+from oscar.apps.catalogue.models import Product
from oscar.test import factories
+class TestContainer(TestCase):
+
+ def test_attributes_initialised_before_write(self):
+ # Regression test for https://github.com/django-oscar/django-oscar/issues/3258
+ product_class = factories.ProductClassFactory()
+ product_class.attributes.create(name='a1', code='a1', required=True)
+ product_class.attributes.create(name='a2', code='a2', required=False)
+ product_class.attributes.create(name='a3', code='a3', required=True)
+ product = factories.ProductFactory(product_class=product_class)
+ product.attr.a1 = "v1"
+ product.attr.a3 = "v3"
+ product.attr.save()
+
+ product = Product.objects.get(pk=product.pk)
+ product.attr.a1 = "v2"
+ product.attr.a3 = "v6"
+ product.attr.save()
+
+ product = Product.objects.get(pk=product.pk)
+ assert product.attr.a1 == "v2"
+ assert product.attr.a3 == "v6"
+
+
class TestBooleanAttributes(TestCase):
def setUp(self):
@@ -52,7 +76,7 @@ def test_save_multi_option_value(self):
product = factories.ProductFactory()
# We'll save two out of the three available options
self.attr.save_value(product, [self.options[0], self.options[2]])
- product.refresh_from_db()
+ product = Product.objects.get(pk=product.pk)
self.assertEqual(list(product.attr.sizes), [self.options[0], self.options[2]])
def test_delete_multi_option_value(self):
@@ -60,7 +84,7 @@ def test_delete_multi_option_value(self):
self.attr.save_value(product, [self.options[0], self.options[1]])
# Now delete these values
self.attr.save_value(product, None)
- product.refresh_from_db()
+ product = Product.objects.get(pk=product.pk)
self.assertFalse(hasattr(product.attr, 'sizes'))
def test_multi_option_value_as_text(self):
| Writing to products attributes with Product.attr can lead to dataloss
### Issue Summary
Writing to products attributes with `product.attr` can lead to data loss
### Steps to Reproduce
Create a productclass with 3 attributes, the second one you create must be optional.
Create a product and do not fill the second optional attribute. Now write to the non-optional attributes with code like this:
p = Product.objects.get(pk=4)
p.attr.subtitle = "lama"
p.attr.available = False
p.attr.save()
One of the 2 attributes will not be updated because the attr object will not be intialized. During save it will encounter the second attribute which is not on the object and trigger initialization. Initialization will overwrite one of the 2 values written and reset it to whatever is in the database.
### Technical details
This problem occurs with all python versions and all oscar versions.
| As a workaround, before writing, just call
```
p.attr.initiate_attributes()
```
@specialunderwear could you please supply a failing test for this? I tried the below but it passes, which suggests I'm not correctly replicating the situation you describe:
```python
def test_attributes_initialised_before_write(self):
product_class = factories.ProductClassFactory()
product_class.attributes.create(name='a1', code='a1', required=True)
product_class.attributes.create(name='a2', code='a2', required=False)
product_class.attributes.create(name='a3', code='a3', required=True)
product = factories.ProductFactory(product_class=product_class)
product.attr.a1 = "v1"
product.attr.a3 = "v3"
product.attr.save()
product.refresh_from_db()
product.attr.a1 = "v2"
product.attr.a3 = "v6"
product.attr.save()
product.refresh_from_db()
assert product.attr.a1 == "v2"
assert product.attr.a3 == "v6"
```
Unfortunately refresh_from_db is not enough to reset the attributes.
try:
```
product.attr.__dict__ = {}
``` | "2020-09-10T12:07:35Z" | 2.1 | [] | [
"tests/integration/catalogue/test_attributes.py::TestContainer::test_attributes_initialised_before_write"
] | [
"tests/integration/catalogue/test_attributes.py::TestBooleanAttributes::test_validate_boolean_values",
"tests/integration/catalogue/test_attributes.py::TestBooleanAttributes::test_validate_invalid_boolean_values",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_delete_multi_option_value",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_multi_option_value_as_text",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_save_multi_option_value",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_validate_invalid_multi_option_values",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_validate_multi_option_values",
"tests/integration/catalogue/test_attributes.py::TestOptionAttributes::test_option_value_as_text",
"tests/integration/catalogue/test_attributes.py::TestDatetimeAttributes::test_validate_datetime_values",
"tests/integration/catalogue/test_attributes.py::TestDatetimeAttributes::test_validate_invalid_datetime_values",
"tests/integration/catalogue/test_attributes.py::TestDateAttributes::test_validate_date_values",
"tests/integration/catalogue/test_attributes.py::TestDateAttributes::test_validate_datetime_values",
"tests/integration/catalogue/test_attributes.py::TestDateAttributes::test_validate_invalid_date_values",
"tests/integration/catalogue/test_attributes.py::TestIntegerAttributes::test_validate_integer_values",
"tests/integration/catalogue/test_attributes.py::TestIntegerAttributes::test_validate_invalid_integer_values",
"tests/integration/catalogue/test_attributes.py::TestIntegerAttributes::test_validate_str_integer_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_float_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_integer_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_invalid_float_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_str_float_values",
"tests/integration/catalogue/test_attributes.py::TestTextAttributes::test_validate_invalid_float_values",
"tests/integration/catalogue/test_attributes.py::TestTextAttributes::test_validate_string_and_unicode_values",
"tests/integration/catalogue/test_attributes.py::TestFileAttributes::test_validate_file_values"
] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,534 | django-oscar__django-oscar-3534 | [
"3510"
] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c | diff --git a/src/oscar/apps/catalogue/abstract_models.py b/src/oscar/apps/catalogue/abstract_models.py
--- a/src/oscar/apps/catalogue/abstract_models.py
+++ b/src/oscar/apps/catalogue/abstract_models.py
@@ -14,6 +14,7 @@
from django.db.models import Count, Exists, OuterRef, Sum
from django.db.models.fields import Field
from django.db.models.lookups import StartsWith
+from django.template.defaultfilters import striptags
from django.urls import reverse
from django.utils.functional import SimpleLazyObject, cached_property
from django.utils.html import strip_tags
@@ -128,6 +129,8 @@ class AbstractCategory(MP_Node):
name = models.CharField(_('Name'), max_length=255, db_index=True)
description = models.TextField(_('Description'), blank=True)
+ meta_title = models.CharField(_('Meta title'), max_length=255, blank=True, null=True)
+ meta_description = models.TextField(_('Meta description'), blank=True, null=True)
image = models.ImageField(_('Image'), upload_to='categories', blank=True,
null=True, max_length=255)
slug = SlugField(_('Slug'), max_length=255, db_index=True)
@@ -235,6 +238,12 @@ def fix_tree(cls, destructive=False):
else:
node.set_ancestors_are_public()
+ def get_meta_title(self):
+ return self.meta_title or self.name
+
+ def get_meta_description(self):
+ return self.meta_description or striptags(self.description)
+
def get_ancestors_and_self(self):
"""
Gets ancestors and includes itself. Use treebeard's get_ancestors
@@ -369,6 +378,8 @@ class AbstractProduct(models.Model):
max_length=255, blank=True)
slug = models.SlugField(_('Slug'), max_length=255, unique=False)
description = models.TextField(_('Description'), blank=True)
+ meta_title = models.CharField(_('Meta title'), max_length=255, blank=True, null=True)
+ meta_description = models.TextField(_('Meta description'), blank=True, null=True)
#: "Kind" of product, e.g. T-Shirt, Book, etc.
#: None for child products, they inherit their parent's product class
@@ -613,6 +624,20 @@ def get_title(self):
return title
get_title.short_description = pgettext_lazy("Product title", "Title")
+ def get_meta_title(self):
+ title = self.meta_title
+ if not title and self.is_child:
+ title = self.parent.meta_title
+ return title or self.get_title()
+ get_meta_title.short_description = pgettext_lazy("Product meta title", "Meta title")
+
+ def get_meta_description(self):
+ meta_description = self.meta_description
+ if not meta_description and self.is_child:
+ meta_description = self.parent.meta_description
+ return meta_description or striptags(self.description)
+ get_meta_description.short_description = pgettext_lazy("Product meta description", "Meta description")
+
def get_product_class(self):
"""
Return a product's item class. Child products inherit their parent's.
diff --git a/src/oscar/apps/catalogue/migrations/0021_auto_20201005_0844.py b/src/oscar/apps/catalogue/migrations/0021_auto_20201005_0844.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/catalogue/migrations/0021_auto_20201005_0844.py
@@ -0,0 +1,33 @@
+# Generated by Django 3.0.10 on 2020-10-05 07:44
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('catalogue', '0020_auto_20200801_0817'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='category',
+ name='meta_description',
+ field=models.TextField(blank=True, null=True, verbose_name='Meta description'),
+ ),
+ migrations.AddField(
+ model_name='category',
+ name='meta_title',
+ field=models.CharField(blank=True, null=True, max_length=255, verbose_name='Meta title'),
+ ),
+ migrations.AddField(
+ model_name='product',
+ name='meta_description',
+ field=models.TextField(blank=True, null=True, verbose_name='Meta description'),
+ ),
+ migrations.AddField(
+ model_name='product',
+ name='meta_title',
+ field=models.CharField(blank=True, null=True, max_length=255, verbose_name='Meta title'),
+ ),
+ ]
diff --git a/src/oscar/apps/dashboard/catalogue/forms.py b/src/oscar/apps/dashboard/catalogue/forms.py
--- a/src/oscar/apps/dashboard/catalogue/forms.py
+++ b/src/oscar/apps/dashboard/catalogue/forms.py
@@ -27,12 +27,25 @@
BaseCategoryForm = movenodeform_factory(
Category,
- fields=['name', 'slug', 'description', 'image', 'is_public'],
- exclude=['ancestors_are_public'])
+ fields=['name', 'slug', 'description', 'image', 'is_public', 'meta_title', 'meta_description'],
+ exclude=['ancestors_are_public'],
+ widgets={'meta_description': forms.Textarea(attrs={'class': 'no-widget-init'})})
-class CategoryForm(BaseCategoryForm):
+class SEOFormMixin:
+ seo_fields = ['meta_title', 'meta_description', 'slug']
+ def primary_form_fields(self):
+ return [field for field in self if not field.is_hidden and not self.is_seo_field(field)]
+
+ def seo_form_fields(self):
+ return [field for field in self if self.is_seo_field(field)]
+
+ def is_seo_field(self, field):
+ return field.name in self.seo_fields
+
+
+class CategoryForm(SEOFormMixin, BaseCategoryForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if 'slug' in self.fields:
@@ -178,7 +191,7 @@ def _attr_image_field(attribute):
label=attribute.name, required=attribute.required)
-class ProductForm(forms.ModelForm):
+class ProductForm(SEOFormMixin, forms.ModelForm):
FIELD_FACTORIES = {
"text": _attr_text_field,
"richtext": _attr_textarea_field,
@@ -198,9 +211,11 @@ class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
- 'title', 'upc', 'description', 'is_public', 'is_discountable', 'structure']
+ 'title', 'upc', 'description', 'is_public', 'is_discountable', 'structure', 'slug', 'meta_title',
+ 'meta_description']
widgets = {
- 'structure': forms.HiddenInput()
+ 'structure': forms.HiddenInput(),
+ 'meta_description': forms.Textarea(attrs={'class': 'no-widget-init'})
}
def __init__(self, product_class, data=None, parent=None, *args, **kwargs):
@@ -220,6 +235,9 @@ def __init__(self, product_class, data=None, parent=None, *args, **kwargs):
self.instance.product_class = product_class
self.add_attribute_fields(product_class, self.instance.is_parent)
+ if 'slug' in self.fields:
+ self.fields['slug'].required = False
+ self.fields['slug'].help_text = _('Leave blank to generate from product title')
if 'title' in self.fields:
self.fields['title'].widget = forms.TextInput(
attrs={'autocomplete': 'off'})
diff --git a/src/oscar/apps/dashboard/catalogue/views.py b/src/oscar/apps/dashboard/catalogue/views.py
--- a/src/oscar/apps/dashboard/catalogue/views.py
+++ b/src/oscar/apps/dashboard/catalogue/views.py
@@ -628,6 +628,9 @@ def get_context_data(self, **kwargs):
def get_success_url(self):
messages.info(self.request, _("Category updated successfully"))
+ action = self.request.POST.get('action')
+ if action == 'continue':
+ return reverse('dashboard:catalogue-category-update', kwargs={"pk": self.object.id})
return super().get_success_url()
| diff --git a/tests/_site/apps/catalogue/migrations/0021_auto_20201005_0844.py b/tests/_site/apps/catalogue/migrations/0021_auto_20201005_0844.py
new file mode 100644
--- /dev/null
+++ b/tests/_site/apps/catalogue/migrations/0021_auto_20201005_0844.py
@@ -0,0 +1,33 @@
+# Generated by Django 3.0.10 on 2020-10-05 07:44
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('catalogue', '0020_auto_20200801_0817'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='category',
+ name='meta_description',
+ field=models.TextField(blank=True, null=True, verbose_name='Meta description'),
+ ),
+ migrations.AddField(
+ model_name='category',
+ name='meta_title',
+ field=models.CharField(blank=True, null=True, max_length=255, verbose_name='Meta title'),
+ ),
+ migrations.AddField(
+ model_name='product',
+ name='meta_description',
+ field=models.TextField(blank=True, null=True, verbose_name='Meta description'),
+ ),
+ migrations.AddField(
+ model_name='product',
+ name='meta_title',
+ field=models.CharField(blank=True, null=True, max_length=255, verbose_name='Meta title'),
+ ),
+ ]
diff --git a/tests/unit/catalogue/test_models.py b/tests/unit/catalogue/test_models.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/catalogue/test_models.py
@@ -0,0 +1,40 @@
+from django.test import TestCase
+
+from oscar.apps.catalogue.models import Product
+from oscar.test.factories.catalogue import ProductFactory
+
+
+class ProductTestCase(TestCase):
+
+ @staticmethod
+ def _get_saved(model_obj):
+ model_obj.save()
+ model_obj.refresh_from_db()
+ return model_obj
+
+ def test_get_meta_title(self):
+ parent_title, child_title = "P title", "C title"
+ parent_meta_title, child_meta_title = "P meta title", "C meta title"
+ parent_product = ProductFactory(structure=Product.PARENT, title=parent_title, meta_title=parent_meta_title)
+ child_product = ProductFactory(structure=Product.CHILD, title=child_title, meta_title=child_meta_title,
+ parent=parent_product)
+ self.assertEqual(child_product.get_meta_title(), child_meta_title)
+ child_product.meta_title = ""
+ self.assertEqual(self._get_saved(child_product).get_meta_title(), parent_meta_title)
+ parent_product.meta_title = ""
+ child_product.parent = self._get_saved(parent_product)
+ self.assertEqual(self._get_saved(child_product).get_meta_title(), child_title)
+
+ def test_get_meta_description(self):
+ parent_description, child_description = "P description", "C description"
+ parent_meta_description, child_meta_description = "P meta description", "C meta description"
+ parent_product = ProductFactory(structure=Product.PARENT, description=parent_description,
+ meta_description=parent_meta_description)
+ child_product = ProductFactory(structure=Product.CHILD, description=child_description,
+ meta_description=child_meta_description, parent=parent_product)
+ self.assertEqual(child_product.get_meta_description(), child_meta_description)
+ child_product.meta_description = ""
+ self.assertEqual(self._get_saved(child_product).get_meta_description(), parent_meta_description)
+ parent_product.meta_description = ""
+ child_product.parent = self._get_saved(parent_product)
+ self.assertEqual(self._get_saved(child_product).get_meta_description(), child_description)
| Add SEO fields to product and category models and make editable in the dashboard
There are a few SEO components that we regularly find clients asking for the ability to control on product and category pages:
1. Meta title
2. Meta description
3. Slug
For products, slug, meta title and description are all auto-generated from the product title/description, with no option to override any of these. While this is fine a lot of the time, Oscar should provide the ability to override these.
For categories, meta title and description are also auto-generated from the product title/description, and there is no option to override.
I think we should have a "Search Engine Optimisation" tab on the dashboard edit views for both of these, which allow override of these parameters.
| Hey @solarissmoke ,
Just wanted to confirm that we are talking about the `AbtractProduct` and `AbstractCategory` classes from `src/oscar/apps/catalogue/abstract_models.py` right?
Also, will this issue involve changes in the model and changes to the frontend (dashboard)?
@SameeranB yes, but note that there is [already a PR](https://github.com/django-oscar/django-oscar/pull/3522) for this feature under review.
Aah... that's great. No issues... I'll look for some other issue to resolve. | "2020-10-05T08:34:15Z" | 2.1 | [] | [
"tests/unit/catalogue/test_models.py::ProductTestCase::test_get_meta_description",
"tests/unit/catalogue/test_models.py::ProductTestCase::test_get_meta_title"
] | [] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,495 | django-oscar__django-oscar-3495 | [
"3074"
] | 8e1381f9c34fce456336028be3d0870836040c41 | diff --git a/src/oscar/apps/address/abstract_models.py b/src/oscar/apps/address/abstract_models.py
--- a/src/oscar/apps/address/abstract_models.py
+++ b/src/oscar/apps/address/abstract_models.py
@@ -103,7 +103,7 @@ class AbstractAddress(models.Model):
'HT': r'^[0-9]{4}$',
'HU': r'^[0-9]{4}$',
'ID': r'^[0-9]{5}$',
- 'IL': r'^[0-9]{7}$',
+ 'IL': r'^([0-9]{5}|[0-9]{7})$',
'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$',
'IN': r'^[0-9]{6}$',
'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$',
| diff --git a/tests/integration/address/test_models.py b/tests/integration/address/test_models.py
--- a/tests/integration/address/test_models.py
+++ b/tests/integration/address/test_models.py
@@ -225,6 +225,8 @@ def test_summary_is_property(self):
('BN', 'BC3615'),
('TW', '104'),
('TW', '10444'),
+ ('IL', '1029200'),
+ ('IL', '94142'),
# It works for small cases as well
('GB', 'sw2 1rw'),
]
| The postal Code validation for Israel should also take 5 digit numbers
In oscar.apps.address.abstract_models.AbstractAddress:
`'IL': r'^[0-9]{7}$',`
Should be:
`'IL': r'^([0-9]{5}|[0-9]{7})$',`
For more info: https://en.wikipedia.org/wiki/Postal_codes_in_Israel
| Right, but seems 5-digit postal codes are not officially used any more, could you please mention working 5-digit postal code?
But they are used by our customers. So sure I can just overwrite it, which we have.
To me the key sentence in the wiki article is: "they continue to be widely used". As we are dealing with people and not machines, then what is official is to me not as important as what is used by our customers :)
@ckaalund grateful if you can make a PR to address this.
Or if you could quote working 5-digit postal code - that also would be helpful.
Ok, found reference by myself of https://en.youbianku.com/Israel.
PR is coming as well.
| "2020-09-08T10:09:09Z" | 2.1 | [] | [
"tests/integration/address/test_models.py::test_assert_valid_postcode[IL-94142]"
] | [
"tests/integration/address/test_models.py::TestUserAddress::test_active_address_fields_skips_whitespace_only_fields",
"tests/integration/address/test_models.py::TestUserAddress::test_can_be_hashed_including_non_ascii",
"tests/integration/address/test_models.py::TestUserAddress::test_converts_postcode_to_uppercase_when_cleaning",
"tests/integration/address/test_models.py::TestUserAddress::test_has_name_property",
"tests/integration/address/test_models.py::TestUserAddress::test_has_summary_property",
"tests/integration/address/test_models.py::TestUserAddress::test_hash_and_summary_values_on_model_with_custom_base_fields",
"tests/integration/address/test_models.py::TestUserAddress::test_hash_and_summary_values_on_model_with_custom_hash_fields",
"tests/integration/address/test_models.py::TestUserAddress::test_hash_value",
"tests/integration/address/test_models.py::TestUserAddress::test_ignores_whitespace_when_hashing",
"tests/integration/address/test_models.py::TestUserAddress::test_populate_shipping_address_doesnt_set_id",
"tests/integration/address/test_models.py::TestUserAddress::test_populated_shipping_address_has_same_summary_user_address",
"tests/integration/address/test_models.py::TestUserAddress::test_strips_whitespace_from_salutation",
"tests/integration/address/test_models.py::TestUserAddress::test_strips_whitespace_in_name_property",
"tests/integration/address/test_models.py::TestUserAddress::test_strips_whitespace_when_cleaning",
"tests/integration/address/test_models.py::TestUserAddress::test_summary_includes_country",
"tests/integration/address/test_models.py::TestUserAddress::test_summary_is_property",
"tests/integration/address/test_models.py::TestUserAddress::test_summary_value",
"tests/integration/address/test_models.py::TestUserAddress::test_uses_city_as_an_alias_of_line4",
"tests/integration/address/test_models.py::TestUserAddress::test_uses_title_firstname_and_lastname_in_salutation",
"tests/integration/address/test_models.py::test_assert_valid_postcode[GB-N1",
"tests/integration/address/test_models.py::test_assert_valid_postcode[SK-991",
"tests/integration/address/test_models.py::test_assert_valid_postcode[CZ-612",
"tests/integration/address/test_models.py::test_assert_valid_postcode[CC-6799]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[CY-8240]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[MC-98000]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[SH-STHL",
"tests/integration/address/test_models.py::test_assert_valid_postcode[JP-150-2345]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[PG-314]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[HN-41202]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[BN-BC3615]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[TW-104]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[TW-10444]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[IL-1029200]",
"tests/integration/address/test_models.py::test_assert_valid_postcode[GB-sw2",
"tests/integration/address/test_models.py::test_assert_invalid_postcode[GB-not-a-postcode]",
"tests/integration/address/test_models.py::test_assert_invalid_postcode[DE-123b4]"
] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,324 | django-oscar__django-oscar-3324 | [
"3323"
] | 5de733e631ad7f914011188f9a3b9a20813ff948 | diff --git a/src/oscar/apps/dashboard/catalogue/views.py b/src/oscar/apps/dashboard/catalogue/views.py
--- a/src/oscar/apps/dashboard/catalogue/views.py
+++ b/src/oscar/apps/dashboard/catalogue/views.py
@@ -646,7 +646,7 @@ class ProductLookupView(ObjectLookupView):
model = Product
def get_queryset(self):
- return self.model.browsable.all()
+ return self.model.objects.browsable().all()
def lookup_filter(self, qs, term):
return qs.filter(Q(title__icontains=term)
| diff --git a/tests/functional/dashboard/test_catalogue.py b/tests/functional/dashboard/test_catalogue.py
--- a/tests/functional/dashboard/test_catalogue.py
+++ b/tests/functional/dashboard/test_catalogue.py
@@ -30,7 +30,8 @@ class TestCatalogueViews(WebTestCase):
def test_exist(self):
urls = [reverse('dashboard:catalogue-product-list'),
reverse('dashboard:catalogue-category-list'),
- reverse('dashboard:stock-alert-list')]
+ reverse('dashboard:stock-alert-list'),
+ reverse('dashboard:catalogue-product-lookup')]
for url in urls:
self.assertIsOk(self.get(url))
| product-lookup not working
### Issue Summary
Can't select related products
### Steps to Reproduce
1. run sandbox
2. in Dashboard->products select any product eg. The shellcoder's handbook
3. in product's upselling click text field `Recommended product:`
4. dropdown contains `The results could not be loaded.` and console throws ` Internal Server Error: /en-gb/dashboard/catalogue/product-lookup/`
with traceback ending
```
django-oscar/src/oscar/apps/dashboard/catalogue/views.py", line 649, in get_queryset
return self.model.browsable.all()
AttributeError: type object 'Product' has no attribute 'browsable'
```
### Technical details
* Python version: 3.7.5
* Django version: 2.2.11
* Oscar version: commit 5de733e
| "2020-03-16T10:36:49Z" | 2.0 | [] | [
"tests/functional/dashboard/test_catalogue.py::TestCatalogueViews::test_exist"
] | [
"tests/functional/dashboard/test_catalogue.py::TestCatalogueViews::test_is_public",
"tests/functional/dashboard/test_catalogue.py::TestCatalogueViews::test_upc_filter",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_create_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_create_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_create_and_continue_editing_a_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_create_product_with_required_attributes",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_delete_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_delete_a_parent_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_delete_a_standalone_product",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_list_her_products",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_can_update_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestAStaffUser::test_cant_create_child_product_for_invalid_parents",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_create_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_create_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_create_and_continue_editing_a_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_create_product_with_required_attributes",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_delete_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_delete_a_parent_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_delete_a_standalone_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_list_her_products",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_can_update_a_product_without_stockrecord",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_cant_create_a_child_product",
"tests/functional/dashboard/test_catalogue.py::TestANonStaffUser::test_cant_create_child_product_for_invalid_parents"
] | 2429ad9e88e9a432dfa60aaca703d99860f85389 |
|
django-oscar/django-oscar | 3,506 | django-oscar__django-oscar-3506 | [
"3428"
] | a3d255dad44ccd78299dd5230f6753f5ab90eacc | diff --git a/src/oscar/apps/checkout/views.py b/src/oscar/apps/checkout/views.py
--- a/src/oscar/apps/checkout/views.py
+++ b/src/oscar/apps/checkout/views.py
@@ -2,6 +2,7 @@
from urllib.parse import quote
from django import http
+from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
from django.shortcuts import redirect
@@ -659,7 +660,14 @@ class ThankYouView(generic.DetailView):
template_name = 'oscar/checkout/thank_you.html'
context_object_name = 'order'
- def get_object(self):
+ def get(self, request, *args, **kwargs):
+ self.object = self.get_object()
+ if self.object is None:
+ return redirect(settings.OSCAR_HOMEPAGE)
+ context = self.get_context_data(object=self.object)
+ return self.render_to_response(context)
+
+ def get_object(self, queryset=None):
# We allow superusers to force an order thank-you page for testing
order = None
if self.request.user.is_superuser:
@@ -674,9 +682,6 @@ def get_object(self):
if 'checkout_order_id' in self.request.session:
order = Order._default_manager.get(
pk=self.request.session['checkout_order_id'])
- else:
- raise http.Http404(_("No order found"))
-
return order
def get_context_data(self, *args, **kwargs):
| diff --git a/tests/functional/checkout/test_customer_checkout.py b/tests/functional/checkout/test_customer_checkout.py
--- a/tests/functional/checkout/test_customer_checkout.py
+++ b/tests/functional/checkout/test_customer_checkout.py
@@ -1,5 +1,3 @@
-from http import client as http_client
-
from django.urls import reverse
from oscar.core.loading import get_class, get_model
@@ -201,10 +199,11 @@ def test_records_use(self):
class TestThankYouView(CheckoutMixin, WebTestCase):
- def tests_gets_a_404_when_there_is_no_order(self):
+ def tests_gets_a_302_when_there_is_no_order(self):
response = self.get(
reverse('checkout:thank-you'), user=self.user, status="*")
- self.assertEqual(http_client.NOT_FOUND, response.status_code)
+ self.assertIsRedirect(response)
+ self.assertRedirectsTo(response, 'catalogue:index')
def tests_custumers_can_reach_the_thank_you_page(self):
self.add_product_to_basket()
@@ -230,7 +229,7 @@ def test_superusers_can_force_an_order(self):
response = self.get(test_url, status='*', user=user)
self.assertIsOk(response)
- def test_users_cannot_force_an_other_custumer_order(self):
+ def test_users_cannot_force_an_other_customer_order(self):
self.add_product_to_basket()
self.enter_shipping_address()
self.place_order()
@@ -241,8 +240,10 @@ def test_users_cannot_force_an_other_custumer_order(self):
test_url = '%s?order_number=%s' % (
reverse('checkout:thank-you'), order.number)
response = self.get(test_url, status='*', user=user)
- self.assertEqual(response.status_code, http_client.NOT_FOUND)
+ self.assertIsRedirect(response)
+ self.assertRedirectsTo(response, 'catalogue:index')
test_url = '%s?order_id=%s' % (reverse('checkout:thank-you'), order.pk)
response = self.get(test_url, status='*', user=user)
- self.assertEqual(response.status_code, http_client.NOT_FOUND)
+ self.assertIsRedirect(response)
+ self.assertRedirectsTo(response, 'catalogue:index')
diff --git a/tests/integration/checkout/test_views.py b/tests/integration/checkout/test_views.py
--- a/tests/integration/checkout/test_views.py
+++ b/tests/integration/checkout/test_views.py
@@ -1,24 +1,32 @@
-from django.test import TestCase
-from django.test.utils import override_settings
from django.urls import reverse
from oscar.test.factories import OrderFactory
+from oscar.test.testcases import WebTestCase
-class ThankYouViewTestCase(TestCase):
+class ThankYouViewTestCase(WebTestCase):
+ is_anonymous = False
- @override_settings(OSCAR_ALLOW_ANON_CHECKOUT=True)
def test_analytics_event_triggered_only_on_first_view(self):
- order = OrderFactory()
- session = self.client.session
- # Put the order ID in the session, mimicking a completed order,
- # so that we can reach the thank you page.
- session['checkout_order_id'] = order.pk
- session.save()
+ with self.settings(OSCAR_ALLOW_ANON_CHECKOUT=True):
+ url = reverse('checkout:thank-you')
+ order = OrderFactory()
+ session = self.client.session
+ # Put the order ID in the session, mimicking a completed order,
+ # so that we can reach the thank you page.
+ session['checkout_order_id'] = order.pk
+ session.save()
- r1 = self.client.get(reverse('checkout:thank-you'), follow=True)
- self.assertTrue(r1.context['send_analytics_event'])
+ r1 = self.client.get(url, follow=True)
+ self.assertTrue(r1.context['send_analytics_event'])
- # Request the view a second time
- r2 = self.client.get(reverse('checkout:thank-you'), follow=True)
- self.assertFalse(r2.context['send_analytics_event'])
+ # Request the view a second time
+ r2 = self.client.get(url, follow=True)
+ self.assertFalse(r2.context['send_analytics_event'])
+
+ def test_missing_order_id_in_the_session(self):
+ with self.settings(OSCAR_ALLOW_ANON_CHECKOUT=True):
+ url = reverse('checkout:thank-you')
+ response = self.app.get(url)
+ self.assertIsRedirect(response)
+ self.assertRedirectsTo(response, 'catalogue:index')
| /oscar/checkout/thank-you/` returns 404 when checkout_order_id not in session
### Issue Summary
Oscar 2.0 smoke tests, `GET /oscar/checkout/thank-you/` returns 404.
The smoke test is obviously requesting this without going through the checkout process, so 403 could be appropriate. It is a very long stretch of the meaning of 404 to use it here - the *resource* was found - it was the resource is responding that it doesnt like the *request* context.
`ThankYouView` has `raise http.Http404(_("No order found"))`
More interesting, it only does this if a session field `checkout_order_id` wasnt found, which that error message does not convey accurately.
If it is about a missing field, it could be a `SuspiciousOperation`.
However as it is a GET, that page URL could be in a users browser history, in which case it could be inadvertently loaded in a new session, which isnt really suspicious, and the user shouldnt see a http error page.
It should be possible to check if there is a successful order by the user, and thank them again! ;-)
Failing that, a "there is no checkout in progress" error message?
### Steps to Reproduce
c.f. setup in https://github.com/django-oscar/django-oscar/issues/3421
### Technical details
* Python version: 3.8
* Django version: 3.0
* Oscar version: 2.0
| A similar issue I'll dump here instead of creating lots of issues.
410 Gone is described in Wikipedia as
> The 410 (Gone) status code indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent. If the origin server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) ought to be used instead.
> The 410 response is primarily intended to assist the task of web maintenance by notifying the recipient that the resource is intentionally unavailable and that the server owners desire that remote links to that resource be removed. Such an event is common for limited-time, promotional services and for resources belonging to individuals no longer associated with the origin server's site. It is not necessary to mark all permanently unavailable resources as "gone" or to keep the mark for any length of time -- that is left to the discretion of the server owner.
> A 410 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see Section 4.2.2 of [RFC7234]).
That is clearly inappropriate here, and even 404 is inappropriate here. Again, 403 or 400 would be more appropriate.
```py
FAIL: test_smoke_GET_oscar/^accounts/^notifications/update/$ (django_smoke_tests.tests.SmokeTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/django_smoke_tests/generator.py", line 95, in test
self_of_test.fail_test(url, method, response=response)
File "/usr/lib/python3.8/site-packages/django_smoke_tests/tests.py", line 44, in fail_test
self.fail(fail_msg)
AssertionError:
SMOKE TEST FAILED
URL: /oscar/accounts/notifications/update/
HTTP METHOD: GET
STATUS CODE: 410
```
> It should be possible to check if there is a successful order by the user, and thank them again! ;-)
Failing that, a "there is no checkout in progress" error message?
Sounds logical to me.
WDYT @django-oscar/core ^ ? | "2020-09-23T11:46:35Z" | 2.1 | [] | [
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::test_users_cannot_force_an_other_customer_order",
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::tests_gets_a_302_when_there_is_no_order"
] | [
"tests/functional/checkout/test_customer_checkout.py::TestIndexView::test_redirects_customers_to_shipping_address_view",
"tests/functional/checkout/test_customer_checkout.py::TestIndexView::test_redirects_customers_with_empty_basket",
"tests/functional/checkout/test_customer_checkout.py::TestIndexView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_can_select_an_existing_shipping_address",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_only_shipping_addresses_are_shown",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestShippingAddressView::test_submitting_valid_form_adds_data_to_session",
"tests/functional/checkout/test_customer_checkout.py::TestUserAddressUpdateView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestUserAddressUpdateView::test_submitting_valid_form_modifies_user_address",
"tests/functional/checkout/test_customer_checkout.py::TestShippingMethodView::test_redirects_when_only_one_shipping_method",
"tests/functional/checkout/test_customer_checkout.py::TestShippingMethodView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestDeleteUserAddressView::test_can_delete_a_user_address_from_shipping_address_page",
"tests/functional/checkout/test_customer_checkout.py::TestDeleteUserAddressView::test_requires_login",
"tests/functional/checkout/test_customer_checkout.py::TestPreviewView::test_allows_order_to_be_placed",
"tests/functional/checkout/test_customer_checkout.py::TestPlacingAnOrderUsingAVoucher::test_records_use",
"tests/functional/checkout/test_customer_checkout.py::TestPlacingAnOrderUsingAnOffer::test_records_use",
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::test_superusers_can_force_an_order",
"tests/functional/checkout/test_customer_checkout.py::TestThankYouView::tests_custumers_can_reach_the_thank_you_page"
] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,316 | django-oscar__django-oscar-3316 | [
"3279"
] | 6fa835e6ae2e51fed7908b5f401f3252aca23b1f | diff --git a/src/oscar/apps/dashboard/vouchers/views.py b/src/oscar/apps/dashboard/vouchers/views.py
--- a/src/oscar/apps/dashboard/vouchers/views.py
+++ b/src/oscar/apps/dashboard/vouchers/views.py
@@ -10,6 +10,7 @@
from django.utils.translation import gettext_lazy as _
from django.views import generic
+from oscar.apps.voucher.utils import get_offer_name
from oscar.core.loading import get_class, get_model
from oscar.core.utils import slugify
from oscar.views import sort_queryset
@@ -113,7 +114,7 @@ def form_valid(self, form):
)
name = form.cleaned_data['name']
offer = ConditionalOffer.objects.create(
- name=_("Offer for voucher '%s'") % name,
+ name=get_offer_name(name),
offer_type=ConditionalOffer.VOUCHER,
benefit=benefit,
condition=condition,
@@ -199,6 +200,7 @@ def form_valid(self, form):
offer.condition.save()
offer.exclusive = form.cleaned_data['exclusive']
+ offer.name = get_offer_name(voucher.name)
offer.save()
benefit = voucher.benefit
@@ -253,7 +255,7 @@ def form_valid(self, form):
)
name = form.cleaned_data['name']
offer = ConditionalOffer.objects.create(
- name=_("Offer for voucher '%s'") % name,
+ name=get_offer_name(name),
offer_type=ConditionalOffer.VOUCHER,
benefit=benefit,
condition=condition,
@@ -322,7 +324,7 @@ def form_valid(self, form):
)
name = form.cleaned_data['name']
offer, __ = ConditionalOffer.objects.update_or_create(
- name=_("Offer for voucher '%s'") % name,
+ name=get_offer_name(name),
defaults=dict(
offer_type=ConditionalOffer.VOUCHER,
benefit=benefit,
diff --git a/src/oscar/apps/voucher/apps.py b/src/oscar/apps/voucher/apps.py
--- a/src/oscar/apps/voucher/apps.py
+++ b/src/oscar/apps/voucher/apps.py
@@ -10,3 +10,4 @@ class VoucherConfig(OscarConfig):
def ready(self):
from . import receivers # noqa
+ from . import signals # noqa
diff --git a/src/oscar/apps/voucher/signals.py b/src/oscar/apps/voucher/signals.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/voucher/signals.py
@@ -0,0 +1,25 @@
+from django.db.models.signals import post_delete
+from django.dispatch import receiver
+
+from oscar.apps.voucher.utils import get_offer_name
+from oscar.core.loading import get_model
+
+Voucher = get_model('voucher', 'Voucher')
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
+
+
+@receiver(post_delete, sender=Voucher)
+def delete_unused_related_conditional_offer(instance, **kwargs):
+ voucher = instance # the object is no longer in the database
+
+ try:
+ conditional_offer = ConditionalOffer.objects.get(
+ name=get_offer_name(voucher.name),
+ offer_type=ConditionalOffer.VOUCHER
+ )
+ except (ConditionalOffer.DoesNotExist, ConditionalOffer.MultipleObjectsReturned):
+ pass
+ else:
+ # Only delete if not used by other vouchers
+ if not conditional_offer.vouchers.exists():
+ conditional_offer.delete()
diff --git a/src/oscar/apps/voucher/utils.py b/src/oscar/apps/voucher/utils.py
--- a/src/oscar/apps/voucher/utils.py
+++ b/src/oscar/apps/voucher/utils.py
@@ -2,6 +2,7 @@
from django.db import connection
from django.utils.crypto import get_random_string
+from django.utils.translation import gettext_lazy as _
def generate_code(length, chars='ABCDEFGHJKLMNPQRSTUVWXYZ23456789',
@@ -33,3 +34,11 @@ def get_unused_code(length=12, group_length=4, separator='-'):
"SELECT 1 FROM voucher_voucher WHERE code=%s", [code])
if not cursor.fetchall():
return code
+
+
+def get_offer_name(voucher_name):
+ """
+ Return the name used for the auto-generated offer created
+ when a voucher is created through the dashboard.
+ """
+ return _("Offer for voucher '%s'") % voucher_name
| diff --git a/tests/integration/voucher/test_models.py b/tests/integration/voucher/test_models.py
--- a/tests/integration/voucher/test_models.py
+++ b/tests/integration/voucher/test_models.py
@@ -5,9 +5,11 @@
from django.core import exceptions
from django.test import TestCase
from django.utils.timezone import utc
+from django.utils.translation import gettext_lazy as _
from oscar.apps.voucher.models import Voucher
from oscar.core.compat import get_user_model
+from oscar.core.loading import get_model
from oscar.test.factories import (
ConditionFactory, OrderFactory, RangeFactory, UserFactory, VoucherFactory,
VoucherSetFactory, create_basket, create_offer, create_product)
@@ -15,6 +17,7 @@
START_DATETIME = datetime.datetime(2011, 1, 1).replace(tzinfo=utc)
END_DATETIME = datetime.datetime(2012, 1, 1).replace(tzinfo=utc)
User = get_user_model()
+ConditionalOffer = get_model('offer', 'ConditionalOffer')
class TestSavingAVoucher(TestCase):
@@ -98,6 +101,93 @@ def test_is_available_to_different_users(self):
self.assertFalse(is_voucher_available_to_user)
+class TestVoucherDelete(TestCase):
+
+ def setUp(self):
+ product = create_product(price=100)
+ self.offer_range = RangeFactory(products=[product])
+ self.offer_condition = ConditionFactory(range=self.offer_range, value=2)
+
+ def test_related_offer_deleted(self):
+ # Voucher with offer name corresponding to it as used in the dashboard
+ voucher_name = "Voucher"
+ voucher = VoucherFactory(name=voucher_name, code="VOUCHER")
+ voucher.offers.add(
+ create_offer(
+ name=_("Offer for voucher '%s'") % voucher_name,
+ offer_type='Voucher',
+ range=self.offer_range,
+ condition=self.offer_condition
+ )
+ )
+
+ voucher.delete()
+ self.assertFalse(
+ ConditionalOffer.objects.filter(
+ name=_("Offer for voucher '%s'") % voucher_name,
+ offer_type=ConditionalOffer.VOUCHER
+ ).exists())
+
+ def test_related_offer_different_name_not_deleted(self):
+ # Voucher with offer named differently
+ voucher = VoucherFactory(name="Voucher", code="VOUCHER")
+ voucher.offers.add(
+ create_offer(
+ name="Different name test",
+ offer_type='Voucher',
+ range=self.offer_range,
+ condition=self.offer_condition
+ )
+ )
+
+ offer_ids = list(voucher.offers.all().values_list('pk', flat=True))
+
+ voucher.delete()
+ count_offers = ConditionalOffer.objects.filter(id__in=offer_ids).count()
+ assert len(offer_ids) == count_offers
+
+ def test_related_offer_different_type_not_deleted(self):
+ # Voucher with offer not of type "Voucher"
+ voucher_name = "Voucher"
+ voucher = VoucherFactory(name=voucher_name, code="VOUCHER")
+ voucher.offers.add(
+ create_offer(
+ name=_("Offer for voucher '%s'") % voucher_name,
+ offer_type='Site',
+ range=self.offer_range,
+ condition=self.offer_condition
+ )
+ )
+
+ offer_ids = list(voucher.offers.all().values_list('pk', flat=True))
+
+ voucher.delete()
+ count_offers = ConditionalOffer.objects.filter(id__in=offer_ids).count()
+ assert len(offer_ids) == count_offers
+
+ def test_multiple_related_offers_not_deleted(self):
+ # Voucher with already used offer
+ voucher_name = "Voucher 1"
+ offer = create_offer(
+ name=_("Offer for voucher '%s'") % voucher_name,
+ offer_type='Voucher',
+ range=self.offer_range,
+ condition=self.offer_condition
+ )
+
+ voucher1 = VoucherFactory(name=voucher_name, code="VOUCHER1")
+ voucher1.offers.add(offer)
+
+ voucher2 = VoucherFactory(name="Voucher 2", code="VOUCHER2")
+ voucher2.offers.add(offer)
+
+ offer_ids = list(voucher1.offers.all().values_list('pk', flat=True))
+
+ voucher1.delete()
+ count_offers = ConditionalOffer.objects.filter(id__in=offer_ids).count()
+ assert len(offer_ids) == count_offers
+
+
class TestAvailableForBasket(TestCase):
def setUp(self):
| Error if create voucher name matching to voucher name deleted
Got error 500 when create voucher
<img width="844" alt="Screen Shot 2020-01-09 at 9 37 03 AM" src="https://user-images.githubusercontent.com/10126934/72033027-a49d3880-32c3-11ea-819e-cbc0c8a9bbde.png">
### Steps to Reproduce
1. Create new voucher
2. Delete that voucher
3. Create voucher again with same **voucher name** deleted
| "2020-03-03T11:07:40Z" | 2.0 | [] | [
"tests/integration/voucher/test_models.py::TestVoucherDelete::test_related_offer_deleted"
] | [
"tests/integration/voucher/test_models.py::TestVoucherSet::test_factory",
"tests/integration/voucher/test_models.py::TestVoucherSet::test_min_count",
"tests/integration/voucher/test_models.py::TestVoucherSet::test_num_basket_additions",
"tests/integration/voucher/test_models.py::TestVoucherSet::test_num_orders",
"tests/integration/voucher/test_models.py::TestSavingAVoucher::test_saves_code_as_uppercase",
"tests/integration/voucher/test_models.py::TestSavingAVoucher::test_verifies_dates_are_sensible",
"tests/integration/voucher/test_models.py::TestAVoucher::test_increments_total_discount_when_recording_usage",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_active_between_start_and_end_dates",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_active_on_end_date",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_active_on_start_date",
"tests/integration/voucher/test_models.py::TestAVoucher::test_is_inactive_outside_of_start_and_end_dates",
"tests/integration/voucher/test_models.py::TestMultiuseVoucher::test_is_available_to_same_user_multiple_times",
"tests/integration/voucher/test_models.py::TestOncePerCustomerVoucher::test_is_available_to_a_user_once",
"tests/integration/voucher/test_models.py::TestOncePerCustomerVoucher::test_is_available_to_different_users",
"tests/integration/voucher/test_models.py::TestVoucherDelete::test_multiple_related_offers_not_deleted",
"tests/integration/voucher/test_models.py::TestVoucherDelete::test_related_offer_different_name_not_deleted",
"tests/integration/voucher/test_models.py::TestVoucherDelete::test_related_offer_different_type_not_deleted",
"tests/integration/voucher/test_models.py::TestAvailableForBasket::test_is_available_for_basket"
] | 2429ad9e88e9a432dfa60aaca703d99860f85389 |
|
django-oscar/django-oscar | 3,505 | django-oscar__django-oscar-3505 | [
"3425"
] | 48cc5c2e622f950a363bed5eff4760d706d098a7 | diff --git a/src/oscar/apps/catalogue/search_handlers.py b/src/oscar/apps/catalogue/search_handlers.py
--- a/src/oscar/apps/catalogue/search_handlers.py
+++ b/src/oscar/apps/catalogue/search_handlers.py
@@ -2,10 +2,11 @@
from django.utils.module_loading import import_string
from django.views.generic.list import MultipleObjectMixin
-from oscar.core.loading import get_class, get_model
+from oscar.core.loading import get_class, get_classes, get_model
BrowseCategoryForm = get_class('search.forms', 'BrowseCategoryForm')
-SearchHandler = get_class('search.search_handlers', 'SearchHandler')
+SearchResultsPaginationMixin, SearchHandler = get_classes(
+ 'search.search_handlers', ('SearchHandler', 'SearchResultsPaginationMixin'))
is_solr_supported = get_class('search.features', 'is_solr_supported')
is_elasticsearch_supported = get_class('search.features', 'is_elasticsearch_supported')
Product = get_model('catalogue', 'Product')
@@ -77,7 +78,7 @@ def get_search_queryset(self):
return sqs
-class SimpleProductSearchHandler(MultipleObjectMixin):
+class SimpleProductSearchHandler(SearchResultsPaginationMixin, MultipleObjectMixin):
"""
A basic implementation of the full-featured SearchHandler that has no
faceting support, but doesn't require a Haystack backend. It only
@@ -89,6 +90,7 @@ class SimpleProductSearchHandler(MultipleObjectMixin):
paginate_by = settings.OSCAR_PRODUCTS_PER_PAGE
def __init__(self, request_data, full_path, categories=None):
+ self.request_data = request_data
self.categories = categories
self.kwargs = {'page': request_data.get('page') or 1}
self.object_list = self.get_queryset()
diff --git a/src/oscar/apps/catalogue/views.py b/src/oscar/apps/catalogue/views.py
--- a/src/oscar/apps/catalogue/views.py
+++ b/src/oscar/apps/catalogue/views.py
@@ -130,11 +130,12 @@ def get(self, request, *args, **kwargs):
try:
self.search_handler = self.get_search_handler(
self.request.GET, request.get_full_path(), [])
+ response = super().get(request, *args, **kwargs)
except InvalidPage:
# Redirect to page one.
messages.error(request, _('The given page number was invalid.'))
return redirect('catalogue:index')
- return super().get(request, *args, **kwargs)
+ return response
def get_search_handler(self, *args, **kwargs):
return get_product_search_handler_class()(*args, **kwargs)
@@ -172,11 +173,12 @@ def get(self, request, *args, **kwargs):
try:
self.search_handler = self.get_search_handler(
request.GET, request.get_full_path(), self.get_categories())
+ response = super().get(request, *args, **kwargs)
except InvalidPage:
messages.error(request, _('The given page number was invalid.'))
return redirect(self.category.get_absolute_url())
- return super().get(request, *args, **kwargs)
+ return response
def is_viewable(self, category, request):
return category.is_public or request.user.is_staff
diff --git a/src/oscar/apps/search/search_handlers.py b/src/oscar/apps/search/search_handlers.py
--- a/src/oscar/apps/search/search_handlers.py
+++ b/src/oscar/apps/search/search_handlers.py
@@ -1,5 +1,4 @@
from django.core.paginator import InvalidPage, Paginator
-from django.utils.translation import gettext_lazy as _
from haystack import connections
from oscar.core.loading import get_class
@@ -9,7 +8,39 @@
FacetMunger = get_class('search.facets', 'FacetMunger')
-class SearchHandler(object):
+class SearchResultsPaginationMixin:
+ paginate_by = None
+ paginator_class = Paginator
+ page_kwarg = 'page'
+
+ def paginate_queryset(self, queryset, page_size):
+ """
+ Paginate the search results. This is a simplified version of
+ Django's MultipleObjectMixin.paginate_queryset
+ """
+ paginator = self.get_paginator(queryset, page_size)
+ page_kwarg = self.page_kwarg
+ page_number = self.request_data.get(page_kwarg, 1)
+ try:
+ page_number = int(page_number)
+ except ValueError:
+ if page_number == 'last':
+ page_number = paginator.num_pages
+ else:
+ raise InvalidPage
+ # This can also raise an InvalidPage exception.
+ page = paginator.page(page_number)
+ return paginator, page, page.object_list, page.has_other_pages()
+
+ def get_paginator(self, queryset, per_page=None):
+ """
+ Return a paginator. Override this to set settings like orphans,
+ allow_empty, etc.
+ """
+ return self.paginator_class(queryset, per_page)
+
+
+class SearchHandler(SearchResultsPaginationMixin):
"""
A class that is concerned with performing a search and paginating the
results. The search is triggered upon initialisation (mainly to have a
@@ -36,9 +67,6 @@ class SearchHandler(object):
form_class = None
model_whitelist = None
- paginate_by = None
- paginator_class = Paginator
- page_kwarg = 'page'
def __init__(self, request_data, full_path):
self.full_path = full_path
@@ -51,8 +79,7 @@ def __init__(self, request_data, full_path):
self.results = self.get_search_results(self.search_form)
# If below raises an UnicodeDecodeError, you're running pysolr < 3.2
# with Solr 4.
- self.paginator, self.page = self.paginate_queryset(
- self.results, request_data)
+ self.paginator, self.page = self.paginate_queryset(self.results, self.paginate_by)[0:2]
# Search related methods
@@ -85,34 +112,6 @@ def get_search_queryset(self):
sqs = sqs.models(*self.model_whitelist)
return sqs
- # Pagination related methods
-
- def paginate_queryset(self, queryset, request_data):
- """
- Paginate the search results. This is a simplified version of
- Django's MultipleObjectMixin.paginate_queryset
- """
- paginator = self.get_paginator(queryset)
- page_kwarg = self.page_kwarg
- page = request_data.get(page_kwarg, 1)
- try:
- page_number = int(page)
- except ValueError:
- if page == 'last':
- page_number = paginator.num_pages
- else:
- raise InvalidPage(_(
- "Page is not 'last', nor can it be converted to an int."))
- # This can also raise an InvalidPage exception.
- return paginator, paginator.page(page_number)
-
- def get_paginator(self, queryset):
- """
- Return a paginator. Override this to set settings like orphans,
- allow_empty, etc.
- """
- return self.paginator_class(queryset, self.paginate_by)
-
# Accessing the search results and meta data
def bulk_fetch_results(self, paginated_results):
| diff --git a/tests/functional/catalogue/test_catalogue.py b/tests/functional/catalogue/test_catalogue.py
--- a/tests/functional/catalogue/test_catalogue.py
+++ b/tests/functional/catalogue/test_catalogue.py
@@ -103,6 +103,13 @@ def test_is_public_off(self):
products_on_page = list(page.context['products'].all())
self.assertEqual(products_on_page, [])
+ def test_invalid_page_redirects_to_index(self):
+ create_product()
+ products_list_url = reverse('catalogue:index')
+ response = self.app.get('%s?page=200' % products_list_url)
+ self.assertEqual(response.status_code, 302)
+ self.assertRedirectsTo(response, 'catalogue:index')
+
class TestProductCategoryView(WebTestCase):
| InvalidPage exceptions in CatalogueView are not properly handled
Found a bug? Please fill out the sections below.
### Issue Summary
Oscar 2.0 (sorry if already fixed..)
If the customer is on page 2 of the Shop product list, and some products are deleted such that there is now only one page, then the customer clicks 'add to cart', they are greeted with a 404 on `
/catalogue/?page=2`
### Steps to Reproduce
1. Create 24 products, and set products to page to 20
2. Navigate to page 2 of the shop
3. Separate tab, delete 20 products but not the one about to be added to cart
4. Back on the shop, click 'add to cart.'
### Technical details
* Python version: 3.8
* Django version: 3.0
* Oscar version: 2.0
| I've retitled the issue because it's not related to adding to cart - the issue is more simply that if you pass an invalid page number to the catalogue view it will always return a 404. We're supposed to be catching the `InvalidPage` exception [here](https://github.com/django-oscar/django-oscar/blob/master/src/oscar/apps/catalogue/views.py#L133) and redirecting to the first page, but the exception is being raised too late, in [`get_context_data()`](https://github.com/django-oscar/django-oscar/blob/master/src/oscar/apps/catalogue/views.py#L145).
That is: https://latest.oscarcommerce.com/en-gb/catalogue/?page=50 should redirect to https://latest.oscarcommerce.com/en-gb/catalogue/ instead of throwing a 404.
Basically, `SimpleProductSearchHandler` inherits `MultipleObjectMixin`, which catches `InvalidPage` and would not allow to propagate it further, but return 404 - https://github.com/django/django/blob/335c9c94acf263901fb023404408880245b0c4b4/django/views/generic/list.py#L71-L75.
Don't have better idea, other than rewrite this method ^.
| "2020-09-23T10:15:23Z" | 3.1 | [] | [
"tests/functional/catalogue/test_catalogue.py::TestProductListView::test_invalid_page_redirects_to_index"
] | [
"tests/functional/catalogue/test_catalogue.py::TestProductDetailView::test_child_to_parent_redirect",
"tests/functional/catalogue/test_catalogue.py::TestProductDetailView::test_enforces_canonical_url",
"tests/functional/catalogue/test_catalogue.py::TestProductDetailView::test_is_public_off",
"tests/functional/catalogue/test_catalogue.py::TestProductDetailView::test_is_public_on",
"tests/functional/catalogue/test_catalogue.py::TestProductListView::test_is_public_off",
"tests/functional/catalogue/test_catalogue.py::TestProductListView::test_is_public_on",
"tests/functional/catalogue/test_catalogue.py::TestProductListView::test_shows_add_to_basket_button_for_available_product",
"tests/functional/catalogue/test_catalogue.py::TestProductListView::test_shows_not_available_for_out_of_stock_product",
"tests/functional/catalogue/test_catalogue.py::TestProductListView::test_shows_pagination_navigation_for_multiple_pages",
"tests/functional/catalogue/test_catalogue.py::TestProductCategoryView::test_browsable_contains_public_child",
"tests/functional/catalogue/test_catalogue.py::TestProductCategoryView::test_browsable_hides_public_child",
"tests/functional/catalogue/test_catalogue.py::TestProductCategoryView::test_browsing_works",
"tests/functional/catalogue/test_catalogue.py::TestProductCategoryView::test_enforces_canonical_url",
"tests/functional/catalogue/test_catalogue.py::TestProductCategoryView::test_is_public_child",
"tests/functional/catalogue/test_catalogue.py::TestProductCategoryView::test_is_public_off",
"tests/functional/catalogue/test_catalogue.py::TestProductCategoryView::test_is_public_on"
] | 0a01977e9cef028bd3e8985309aa4741b6a8cb33 |
django-oscar/django-oscar | 3,317 | django-oscar__django-oscar-3317 | [
"3282"
] | 40a4cacc27223ac675f5e859e7568b632e3f304c | diff --git a/src/oscar/apps/catalogue/abstract_models.py b/src/oscar/apps/catalogue/abstract_models.py
--- a/src/oscar/apps/catalogue/abstract_models.py
+++ b/src/oscar/apps/catalogue/abstract_models.py
@@ -851,6 +851,10 @@ def is_file(self):
def __str__(self):
return self.name
+ def clean(self):
+ if self.type == self.BOOLEAN and self.required:
+ raise ValidationError(_("Boolean attribute should not be required."))
+
def _save_file(self, value_obj, value):
# File fields in Django are treated differently, see
# django.db.models.fields.FileField and method save_form_data
| diff --git a/tests/integration/catalogue/test_models.py b/tests/integration/catalogue/test_models.py
--- a/tests/integration/catalogue/test_models.py
+++ b/tests/integration/catalogue/test_models.py
@@ -19,3 +19,9 @@ def test_product_attributes_cant_be_python_keywords():
attr = models.ProductAttribute(name="A", code="import")
with pytest.raises(ValidationError):
attr.full_clean()
+
+
+def test_product_boolean_attribute_cant_be_required():
+ attr = models.ProductAttribute(name="A", code="a", type=models.ProductAttribute.BOOLEAN, required=True)
+ with pytest.raises(ValidationError):
+ attr.full_clean()
| Setting `required` on a ProductAttribute with type boolean is non-sensical
### Issue Summary
When a `ProductAttribute` with type `boolean` is set to `required=True`, it requires any underlying`ProductAttributeValue` to be set to `True`, otherwise the Product you're trying to create/change won't save in the dashboard. I don't think the `required` field makes sense for a boolean field in this case. A Boolean field could still be `False` but be required to be filled in as `False`. It's all a bit confusing.
It makes sense purely on a form, where you might need to check a checkbox to submit the form. But in this case it's a field in a database that's required.
### Steps to Reproduce
1. Go to dashboard
1. On any `ProductType` defined, add an Attribute with type `True / False` and set the `Required` field to `True`.
1. Create a new product with this `ProductType` and set the attribute on the product to `False`
The dashboard interface says it's required to be set to `True` and as such the option for `False` is not possible.
### Proposed solution
Don't allow `ProductAttribute`'s with type `boolean` to be set to `required=True`.
### Technical details
I've tested this on an older Python version. But couldn't find any reference of a fix for this in the latest version.
* Python version: `2.7.17`
* Django version: `1.11.23`
* Oscar version: `1.6.7 `
| Thanks for this - your proposed fix makes sense, PR welcome if you have time. | "2020-03-03T20:06:50Z" | 2.0 | [] | [
"tests/integration/catalogue/test_models.py::test_product_boolean_attribute_cant_be_required"
] | [
"tests/integration/catalogue/test_models.py::test_product_attributes_can_contain_underscores",
"tests/integration/catalogue/test_models.py::test_product_attributes_cant_contain_hyphens",
"tests/integration/catalogue/test_models.py::test_product_attributes_cant_be_python_keywords"
] | 2429ad9e88e9a432dfa60aaca703d99860f85389 |
django-oscar/django-oscar | 3,677 | django-oscar__django-oscar-3677 | [
"3675"
] | ce95a8f742c18ce4ee2c9b2556d969cf654e85d7 | diff --git a/src/oscar/apps/customer/history.py b/src/oscar/apps/customer/history.py
--- a/src/oscar/apps/customer/history.py
+++ b/src/oscar/apps/customer/history.py
@@ -7,61 +7,67 @@
Product = get_model('catalogue', 'Product')
-def get(request):
- """
- Return a list of recently viewed products
- """
- ids = extract(request)
-
- # Reordering as the ID order gets messed up in the query
- product_dict = Product.objects.browsable().in_bulk(ids)
- ids.reverse()
- return [product_dict[id] for id in ids if id in product_dict]
-
-
-def extract(request, response=None):
- """
- Extract the IDs of products in the history cookie
- """
- ids = []
+class CustomerHistoryManager:
cookie_name = settings.OSCAR_RECENTLY_VIEWED_COOKIE_NAME
- if cookie_name in request.COOKIES:
- try:
- ids = json.loads(request.COOKIES[cookie_name])
- except ValueError:
- # This can occur if something messes up the cookie
- if response:
- response.delete_cookie(cookie_name)
- else:
- # Badly written web crawlers send garbage in double quotes
- if not isinstance(ids, list):
- ids = []
- return ids
+ cookie_kwargs = {
+ 'max_age': settings.OSCAR_RECENTLY_VIEWED_COOKIE_LIFETIME,
+ 'secure': settings.OSCAR_RECENTLY_VIEWED_COOKIE_SECURE,
+ 'httponly': True,
+ }
+ max_products = settings.OSCAR_RECENTLY_VIEWED_PRODUCTS
+ @classmethod
+ def get(cls, request):
+ """
+ Return a list of recently viewed products
+ """
+ ids = cls.extract(request)
-def add(ids, new_id):
- """
- Add a new product ID to the list of product IDs
- """
- max_products = settings.OSCAR_RECENTLY_VIEWED_PRODUCTS
- if new_id in ids:
- ids.remove(new_id)
- ids.append(new_id)
- if (len(ids) > max_products):
- ids = ids[len(ids) - max_products:]
- return ids
+ # Reordering as the ID order gets messed up in the query
+ product_dict = Product.objects.browsable().in_bulk(ids)
+ ids.reverse()
+ return [product_dict[product_id] for product_id in ids if product_id in product_dict]
+
+ @classmethod
+ def extract(cls, request, response=None):
+ """
+ Extract the IDs of products in the history cookie
+ """
+ ids = []
+ if cls.cookie_name in request.COOKIES:
+ try:
+ ids = json.loads(request.COOKIES[cls.cookie_name])
+ except ValueError:
+ # This can occur if something messes up the cookie
+ if response:
+ response.delete_cookie(cls.cookie_name)
+ else:
+ # Badly written web crawlers send garbage in double quotes
+ if not isinstance(ids, list):
+ ids = []
+ return ids
+ @classmethod
+ def add(cls, ids, new_id):
+ """
+ Add a new product ID to the list of product IDs
+ """
+ if new_id in ids:
+ ids.remove(new_id)
+ ids.append(new_id)
+ if len(ids) > cls.max_products:
+ ids = ids[len(ids) - cls.max_products:]
+ return ids
-def update(product, request, response):
- """
- Updates the cookies that store the recently viewed products
- removing possible duplicates.
- """
- ids = extract(request, response)
- updated_ids = add(ids, product.id)
- response.set_cookie(
- settings.OSCAR_RECENTLY_VIEWED_COOKIE_NAME,
- json.dumps(updated_ids),
- max_age=settings.OSCAR_RECENTLY_VIEWED_COOKIE_LIFETIME,
- secure=settings.OSCAR_RECENTLY_VIEWED_COOKIE_SECURE,
- httponly=True)
+ @classmethod
+ def update(cls, product, request, response):
+ """
+ Updates the cookies that store the recently viewed products
+ removing possible duplicates.
+ """
+ ids = cls.extract(request, response)
+ updated_ids = cls.add(ids, product.id)
+ response.set_cookie(
+ cls.cookie_name,
+ json.dumps(updated_ids),
+ **cls.cookie_kwargs)
diff --git a/src/oscar/apps/customer/receivers.py b/src/oscar/apps/customer/receivers.py
--- a/src/oscar/apps/customer/receivers.py
+++ b/src/oscar/apps/customer/receivers.py
@@ -1,8 +1,9 @@
from django.dispatch import receiver
from oscar.apps.catalogue.signals import product_viewed
+from oscar.core.loading import get_class
-from . import history
+CustomerHistoryManager = get_class('customer.history', 'CustomerHistoryManager')
@receiver(product_viewed)
@@ -12,4 +13,4 @@ def receive_product_view(sender, product, user, request, response, **kwargs):
Requires the request and response objects due to dependence on cookies
"""
- return history.update(product, request, response)
+ return CustomerHistoryManager.update(product, request, response)
diff --git a/src/oscar/templatetags/history_tags.py b/src/oscar/templatetags/history_tags.py
--- a/src/oscar/templatetags/history_tags.py
+++ b/src/oscar/templatetags/history_tags.py
@@ -4,10 +4,10 @@
from django.urls import Resolver404, resolve
from django.utils.translation import gettext_lazy as _
-from oscar.apps.customer import history
-from oscar.core.loading import get_model
+from oscar.core.loading import get_class, get_model
Site = get_model('sites', 'Site')
+CustomerHistoryManager = get_class('customer.history', 'CustomerHistoryManager')
register = template.Library()
@@ -19,7 +19,7 @@ def recently_viewed_products(context, current_product=None):
Inclusion tag listing the most recently viewed products
"""
request = context['request']
- products = history.get(request)
+ products = CustomerHistoryManager.get(request)
if current_product:
products = [p for p in products if p != current_product]
return {'products': products,
| diff --git a/tests/functional/customer/test_history.py b/tests/functional/customer/test_history.py
--- a/tests/functional/customer/test_history.py
+++ b/tests/functional/customer/test_history.py
@@ -4,12 +4,13 @@
from django.http import HttpRequest
from django.urls import reverse
-from oscar.apps.customer import history
from oscar.core.compat import get_user_model
+from oscar.core.loading import get_class
from oscar.templatetags.history_tags import get_back_button
from oscar.test.factories import create_product
from oscar.test.testcases import WebTestCase
+CustomerHistoryManager = get_class('customer.history', 'CustomerHistoryManager')
User = get_user_model()
COOKIE_NAME = settings.OSCAR_RECENTLY_VIEWED_COOKIE_NAME
@@ -27,7 +28,7 @@ def test_id_gets_added_to_cookie(self):
response = self.app.get(self.product.get_absolute_url())
request = HttpRequest()
request.COOKIES[COOKIE_NAME] = _unquote(response.test_app.cookies[COOKIE_NAME])
- self.assertTrue(self.product.id in history.extract(request))
+ self.assertTrue(self.product.id in CustomerHistoryManager.extract(request))
def test_get_back_button(self):
request = HttpRequest()
diff --git a/tests/integration/customer/test_history.py b/tests/integration/customer/test_history.py
--- a/tests/integration/customer/test_history.py
+++ b/tests/integration/customer/test_history.py
@@ -1,7 +1,9 @@
from django import http
from django.test import TestCase
-from oscar.apps.customer import history
+from oscar.core.loading import get_class
+
+CustomerHistoryManager = get_class('customer.history', 'CustomerHistoryManager')
class TestProductHistory(TestCase):
@@ -11,5 +13,5 @@ def setUp(self):
self.response = http.HttpResponse()
def test_starts_with_empty_list(self):
- products = history.get(self.request)
+ products = CustomerHistoryManager.get(self.request)
self.assertEqual([], products)
| Load customer.history with get_class
### Issue Summary
All functions of customer.history are loaded by using direct import instead of `get_class`, making it very impractical to override.
### Steps to Reproduce
Use cases are for example if you want to change how the object are loaded when getting recently viewed products (I wanted to use search backend instead of DB), or if you want to change some properties of the oscar_history cookie (I wanted to set `samesite` to Lax). Not all use cases can be anticipated, hence this is a good candidate for a `get_class` encapsulation. I think, contrarily to its name, that `get_class` also works for module import, but history module could also be converted to a class with static methods, what would you prefer? I can do the pull request then.
### Technical details
* Python version: 3.9.1
* Django version: 3.1.6
* Oscar version: 3.0.0
| Thanks @Chadys - this should definitely be loaded dynamically. As you note `get_class` does in fact work with modules, but I think moving these functions to a class with static methods would be helpful and more extensible in future. PR would be appreciated. | "2021-03-09T19:07:19Z" | 3.0 | [] | [
"tests/functional/customer/test_history.py::HistoryHelpersTest::test_get_back_button",
"tests/functional/customer/test_history.py::HistoryHelpersTest::test_id_gets_added_to_cookie",
"tests/functional/customer/test_history.py::HistoryHelpersTest::test_viewing_product_creates_cookie",
"tests/functional/customer/test_history.py::TestAUserWhoLogsOut::test_has_their_cookies_deleted_on_logout",
"tests/integration/customer/test_history.py::TestProductHistory::test_starts_with_empty_list"
] | [] | 04cd6a4fc750db9310147d96776f06fe289269bf |
django-oscar/django-oscar | 3,501 | django-oscar__django-oscar-3501 | [
"2772"
] | f333a827734761d8f1b21db94f5ae9654be31169 | diff --git a/src/oscar/apps/analytics/reports.py b/src/oscar/apps/analytics/reports.py
--- a/src/oscar/apps/analytics/reports.py
+++ b/src/oscar/apps/analytics/reports.py
@@ -37,6 +37,7 @@ class ProductReportHTMLFormatter(ReportHTMLFormatter):
class ProductReportGenerator(ReportGenerator):
code = 'product_analytics'
description = _('Product analytics')
+ model_class = ProductRecord
formatters = {
'CSV_formatter': ProductReportCSVFormatter,
@@ -45,10 +46,6 @@ class ProductReportGenerator(ReportGenerator):
def report_description(self):
return self.description
- def generate(self):
- records = ProductRecord._default_manager.all()
- return self.formatter.generate_response(records)
-
def is_available_to(self, user):
return user.is_staff
@@ -89,14 +86,11 @@ class UserReportHTMLFormatter(ReportHTMLFormatter):
class UserReportGenerator(ReportGenerator):
code = 'user_analytics'
description = _('User analytics')
+ queryset = UserRecord._default_manager.select_related().all()
formatters = {
'CSV_formatter': UserReportCSVFormatter,
'HTML_formatter': UserReportHTMLFormatter}
- def generate(self):
- users = UserRecord._default_manager.select_related().all()
- return self.formatter.generate_response(users)
-
def is_available_to(self, user):
return user.is_staff
diff --git a/src/oscar/apps/basket/reports.py b/src/oscar/apps/basket/reports.py
--- a/src/oscar/apps/basket/reports.py
+++ b/src/oscar/apps/basket/reports.py
@@ -56,6 +56,7 @@ class OpenBasketReportGenerator(ReportGenerator):
code = 'open_baskets'
description = _('Open baskets')
date_range_field_name = 'date_created'
+ queryset = Basket._default_manager.filter(status=Basket.OPEN)
formatters = {
'CSV_formatter': OpenBasketReportCSVFormatter,
@@ -65,8 +66,7 @@ def generate(self):
additional_data = {
'start_date': self.start_date,
'end_date': self.end_date}
- baskets = Basket._default_manager.filter(status=Basket.OPEN)
- return self.formatter.generate_response(baskets, **additional_data)
+ return self.formatter.generate_response(self.queryset, **additional_data)
class SubmittedBasketReportCSVFormatter(ReportCSVFormatter):
@@ -110,6 +110,7 @@ class SubmittedBasketReportGenerator(ReportGenerator):
code = 'submitted_baskets'
description = _('Submitted baskets')
date_range_field_name = 'date_submitted'
+ queryset = Basket._default_manager.filter(status=Basket.SUBMITTED)
formatters = {
'CSV_formatter': SubmittedBasketReportCSVFormatter,
@@ -119,5 +120,4 @@ def generate(self):
additional_data = {
'start_date': self.start_date,
'end_date': self.end_date}
- baskets = Basket._default_manager.filter(status=Basket.SUBMITTED)
- return self.formatter.generate_response(baskets, **additional_data)
+ return self.formatter.generate_response(self.queryset, **additional_data)
diff --git a/src/oscar/apps/dashboard/reports/reports.py b/src/oscar/apps/dashboard/reports/reports.py
--- a/src/oscar/apps/dashboard/reports/reports.py
+++ b/src/oscar/apps/dashboard/reports/reports.py
@@ -19,13 +19,17 @@ class ReportGenerator(object):
code = ''
description = '<insert report description>'
date_range_field_name = None
+ model_class = None
+ queryset = None
def __init__(self, **kwargs):
self.start_date = kwargs.get('start_date')
self.end_date = kwargs.get('end_date')
- formatter_name = '%s_formatter' % kwargs['formatter']
+ formatter_name = '%s_formatter' % kwargs.get('formatter', 'HTML')
self.formatter = self.formatters[formatter_name]()
+ self.queryset = self.get_queryset()
+ self.queryset = self.filter_with_date_range(self.queryset)
def report_description(self):
return _('%(report_filter)s between %(start_date)s and %(end_date)s') \
@@ -34,8 +38,19 @@ def report_description(self):
'end_date': date(self.end_date, 'DATE_FORMAT')
}
+ def get_queryset(self):
+ if self.queryset is not None:
+ return self.queryset
+
+ if not self.model_class:
+ raise ValueError(
+ "Please define a model_class property on your report generator class, "
+ "or override the qet_queryset() method."
+ )
+ return self.model_class._default_manager.all()
+
def generate(self):
- pass
+ return self.formatter.generate_response(self.queryset)
def filename(self):
"""
diff --git a/src/oscar/apps/dashboard/reports/views.py b/src/oscar/apps/dashboard/reports/views.py
--- a/src/oscar/apps/dashboard/reports/views.py
+++ b/src/oscar/apps/dashboard/reports/views.py
@@ -47,7 +47,8 @@ def get(self, request, *args, **kwargs):
if form.cleaned_data['download']:
return report
else:
- self.set_list_view_attrs(generator, report)
+ self.template_name = generator.filename()
+ self.object_list = self.queryset = generator.queryset
context = self.get_context_data(object_list=self.queryset)
context['form'] = form
context['description'] = generator.report_description()
@@ -55,8 +56,3 @@ def get(self, request, *args, **kwargs):
else:
form = self.report_form_class()
return TemplateResponse(request, self.template_name, {'form': form})
-
- def set_list_view_attrs(self, generator, report):
- self.template_name = generator.filename()
- queryset = generator.filter_with_date_range(report)
- self.object_list = self.queryset = queryset
diff --git a/src/oscar/apps/offer/reports.py b/src/oscar/apps/offer/reports.py
--- a/src/oscar/apps/offer/reports.py
+++ b/src/oscar/apps/offer/reports.py
@@ -42,15 +42,17 @@ class OfferReportGenerator(ReportGenerator):
'HTML_formatter': OfferReportHTMLFormatter,
}
- def generate(self):
+ def get_queryset(self):
qs = OrderDiscount._default_manager.all()
if self.start_date:
qs = qs.filter(order__date_placed__gte=self.start_date)
if self.end_date:
qs = qs.filter(order__date_placed__lt=self.end_date + datetime.timedelta(days=1))
+ return qs
+ def generate(self):
offer_discounts = {}
- for discount in qs:
+ for discount in self.queryset:
if discount.offer_id not in offer_discounts:
try:
all_offers = ConditionalOffer._default_manager
diff --git a/src/oscar/apps/order/reports.py b/src/oscar/apps/order/reports.py
--- a/src/oscar/apps/order/reports.py
+++ b/src/oscar/apps/order/reports.py
@@ -51,21 +51,21 @@ class OrderReportGenerator(ReportGenerator):
'HTML_formatter': OrderReportHTMLFormatter,
}
- def generate(self):
+ def get_queryset(self):
qs = Order._default_manager.all()
-
if self.start_date:
qs = qs.filter(date_placed__gte=self.start_date)
if self.end_date:
qs = qs.filter(
date_placed__lt=self.end_date + datetime.timedelta(days=1))
+ return qs
+ def generate(self):
additional_data = {
'start_date': self.start_date,
'end_date': self.end_date
}
-
- return self.formatter.generate_response(qs, **additional_data)
+ return self.formatter.generate_response(self.queryset, **additional_data)
def is_available_to(self, user):
return user.is_staff
diff --git a/src/oscar/apps/voucher/reports.py b/src/oscar/apps/voucher/reports.py
--- a/src/oscar/apps/voucher/reports.py
+++ b/src/oscar/apps/voucher/reports.py
@@ -34,14 +34,10 @@ class VoucherReportHTMLFormatter(ReportHTMLFormatter):
class VoucherReportGenerator(ReportGenerator):
-
code = 'vouchers'
description = _('Voucher performance')
+ model_class = Voucher
formatters = {
'CSV_formatter': VoucherReportCSVFormatter,
'HTML_formatter': VoucherReportHTMLFormatter}
-
- def generate(self):
- vouchers = Voucher._default_manager.all()
- return self.formatter.generate_response(vouchers)
| diff --git a/tests/integration/basket/test_report.py b/tests/integration/basket/test_report.py
--- a/tests/integration/basket/test_report.py
+++ b/tests/integration/basket/test_report.py
@@ -1,12 +1,21 @@
import datetime
from django.test import TestCase
+from django.utils.timezone import utc
+from freezegun import freeze_time
from oscar.apps.basket.reports import (
OpenBasketReportGenerator, SubmittedBasketReportGenerator)
+from oscar.core.loading import get_model
+from oscar.test.factories import BasketFactory
+
+Basket = get_model('basket', 'Basket')
class TestBasketReports(TestCase):
+ def setUp(self) -> None:
+ BasketFactory.create_batch(5, status=Basket.OPEN)
+ BasketFactory.create_batch(6, status=Basket.SUBMITTED)
def test_open_report_doesnt_error(self):
data = {
@@ -17,6 +26,21 @@ def test_open_report_doesnt_error(self):
generator = OpenBasketReportGenerator(**data)
generator.generate()
+ def test_open_report_queryset(self):
+ generator = OpenBasketReportGenerator()
+ assert generator.queryset.count() == 5
+
+ @freeze_time('2020-05-02')
+ def test_open_report_filtering_by_date_range(self):
+ BasketFactory.create(status=Basket.OPEN)
+ data = {
+ 'start_date': datetime.date(2020, 5, 1),
+ 'end_date': datetime.date(2020, 6, 1),
+ 'formatter': 'CSV'
+ }
+ generator = OpenBasketReportGenerator(**data)
+ assert generator.queryset.count() == 1
+
def test_submitted_report_doesnt_error(self):
data = {
'start_date': datetime.date(2012, 5, 1),
@@ -25,3 +49,18 @@ def test_submitted_report_doesnt_error(self):
}
generator = SubmittedBasketReportGenerator(**data)
generator.generate()
+
+ def test_submitted_report_queryset(self):
+ generator = SubmittedBasketReportGenerator()
+ assert generator.queryset.count() == 6
+
+ def test_submitted_report_filtering_by_date_range(self):
+ date_submitted = datetime.datetime(2020, 7, 3).replace(tzinfo=utc)
+ BasketFactory.create(status=Basket.SUBMITTED, date_submitted=date_submitted)
+ data = {
+ 'start_date': datetime.date(2020, 7, 1),
+ 'end_date': datetime.date(2020, 8, 1),
+ 'formatter': 'CSV'
+ }
+ generator = SubmittedBasketReportGenerator(**data)
+ assert generator.queryset.count() == 1
| "Product analytics" report on dashboard ignores date range
Found a bug? Please fill out the sections below.
### Issue Summary
"Product analytics" report on dashboard ignores date range
### Steps to Reproduce
Visit the dashboard, click on the "Reports" tab.
Select "Product analytics" from the "Report type" dropdown.
Select a date range and click "generate report"
The results returned will always be for all time, despite the date range selected
### Technical details
Any Python / Django version, Oscar 1.6.2
The ProductReportGenerator ignores the date range, and the stored analytics do not keep track of it. It might be nice to disable the date range controls for those reports that will never store date information. Though a date breakdown of products purchased would be a nice to have...
| You could add a new model <Insert Name Here> that contains the values on ProductRecord and has a Foreign Key to ProductRecord. This model is created/updated for each day. (If no views/additions/purchases are made then the objects would not be created) The model would have a date for that day for filtering purposes.
Just a note that "User analytics" behave in the same way
Date filtering is definitely broken for CSV exports. The [function that performs the filtering](https://github.com/django-oscar/django-oscar/blob/master/src/oscar/apps/dashboard/reports/views.py#L59) is [never called](https://github.com/django-oscar/django-oscar/blob/master/src/oscar/apps/dashboard/reports/views.py#L48) for CSV downloads. It also wouldn't work because the CSV formatter's `generate()` returns a response. | "2020-09-21T11:54:51Z" | 2.1 | [] | [
"tests/integration/basket/test_report.py::TestBasketReports::test_open_report_filtering_by_date_range",
"tests/integration/basket/test_report.py::TestBasketReports::test_open_report_queryset",
"tests/integration/basket/test_report.py::TestBasketReports::test_submitted_report_filtering_by_date_range",
"tests/integration/basket/test_report.py::TestBasketReports::test_submitted_report_queryset"
] | [
"tests/integration/basket/test_report.py::TestBasketReports::test_open_report_doesnt_error",
"tests/integration/basket/test_report.py::TestBasketReports::test_submitted_report_doesnt_error"
] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |
django-oscar/django-oscar | 3,886 | django-oscar__django-oscar-3886 | [
"3885"
] | 0a01977e9cef028bd3e8985309aa4741b6a8cb33 | diff --git a/src/oscar/apps/dashboard/offers/forms.py b/src/oscar/apps/dashboard/offers/forms.py
--- a/src/oscar/apps/dashboard/offers/forms.py
+++ b/src/oscar/apps/dashboard/offers/forms.py
@@ -123,11 +123,17 @@ def clean(self):
# Check that either a condition has been entered or a custom condition
# has been chosen
- if data.get('custom_condition'):
- if not data.get('range', None):
+ if not any(data.values()):
+ raise forms.ValidationError(
+ _("Please either choose a range, type and value OR "
+ "select a custom condition"))
+
+ if data['custom_condition']:
+ if data.get('range') or data.get('type') or data.get('value'):
raise forms.ValidationError(
- _("A range is required"))
- elif not all([data.get('range'), data.get('type'), data.get('value')]):
+ _("No other options can be set if you are using a "
+ "custom condition"))
+ elif not data.get('type'):
raise forms.ValidationError(
_("Please either choose a range, type and value OR "
"select a custom condition"))
diff --git a/src/oscar/apps/offer/abstract_models.py b/src/oscar/apps/offer/abstract_models.py
--- a/src/oscar/apps/offer/abstract_models.py
+++ b/src/oscar/apps/offer/abstract_models.py
@@ -732,6 +732,50 @@ def proxy_map(self):
'offer.conditions', 'CoverageCondition'),
}
+ def clean(self):
+ # The form will validate whether this is ok or not.
+ if not self.type:
+ return
+ method_name = 'clean_%s' % self.type.lower()
+ if hasattr(self, method_name):
+ getattr(self, method_name)()
+
+ def clean_count(self):
+ errors = []
+
+ if not self.range:
+ errors.append(_("Count conditions require a product range"))
+
+ if not self.value:
+ errors.append(_("Count conditions require a value"))
+
+ if errors:
+ raise exceptions.ValidationError(errors)
+
+ def clean_value(self):
+ errors = []
+
+ if not self.range:
+ errors.append(_("Value conditions require a product range"))
+
+ if not self.value:
+ errors.append(_("Value conditions require a value"))
+
+ if errors:
+ raise exceptions.ValidationError(errors)
+
+ def clean_coverage(self):
+ errors = []
+
+ if not self.range:
+ errors.append(_("Coverage conditions require a product range"))
+
+ if not self.value:
+ errors.append(_("Coverage conditions require a value"))
+
+ if errors:
+ raise exceptions.ValidationError(errors)
+
def consume_items(self, offer, basket, affected_lines):
pass
| diff --git a/tests/integration/dashboard/test_offer_forms.py b/tests/integration/dashboard/test_offer_forms.py
--- a/tests/integration/dashboard/test_offer_forms.py
+++ b/tests/integration/dashboard/test_offer_forms.py
@@ -202,14 +202,34 @@ def test_clean_no_value(self):
def test_clean_custom_condition(self):
"""
- If a custom condition exists, and the data for range and custom condition is supplied,
- the form should be valid.
+ If a custom condition is selected, the form should be valid.
"""
custom_condition = create_condition(CustomConditionModel)
form = forms.ConditionForm(data={
- 'range': self.range.id,
+ 'range': '',
'type': '',
'value': '',
'custom_condition': custom_condition.id
})
self.assertTrue(form.is_valid())
+ self.assertEqual({
+ 'range': None,
+ 'type': '',
+ 'value': None,
+ 'custom_condition': str(custom_condition.id)
+ }, form.clean())
+
+ def test_clean_custom_condition_with_range_type_and_value(self):
+ """
+ If a custom condition is selected, but a range, type and value is selected as well,
+ it should throw a ValidationError as you may only have a custom condition.
+ """
+ custom_condition = create_condition(CustomConditionModel)
+ form = forms.ConditionForm(data={
+ 'range': self.range.id,
+ 'type': 'Count',
+ 'value': '5',
+ 'custom_condition': custom_condition.id
+ })
+ self.assertFalse(form.is_valid())
+ self.assertRaises(ValidationError, form.clean)
diff --git a/tests/integration/dashboard/test_offer_views.py b/tests/integration/dashboard/test_offer_views.py
--- a/tests/integration/dashboard/test_offer_views.py
+++ b/tests/integration/dashboard/test_offer_views.py
@@ -356,11 +356,9 @@ def test_offer_condition_view_with_built_in_condition_type(self):
}])
def test_offer_condition_view_with_custom_condition_type(self):
- range_ = RangeFactory()
condition = create_condition(CustomConditionModel)
request = RequestFactory().post('/', data={
- 'range': range_.pk,
'custom_condition': condition.pk,
})
request.session['offer_wizard'] = {
@@ -379,7 +377,7 @@ def test_offer_condition_view_with_custom_condition_type(self):
self.assertJSONEqual(request.session['offer_wizard']['benefit_obj'], self.benefit_obj_session_data)
self.assertJSONEqual(request.session['offer_wizard']['condition'], {
'data': {
- 'range': range_.pk,
+ 'range': None,
'type': '',
'value': None,
'custom_condition': str(condition.pk),
@@ -669,11 +667,9 @@ def test_offer_condition_view_with_built_in_condition_type(self):
}])
def test_offer_condition_view_with_custom_condition_type(self):
- range_ = RangeFactory()
condition = create_condition(CustomConditionModel)
request = RequestFactory().post('/', data={
- 'range': range_.pk,
'custom_condition': condition.pk,
})
request.session['offer_wizard'] = {
@@ -694,7 +690,7 @@ def test_offer_condition_view_with_custom_condition_type(self):
self.assertJSONEqual(request.session['offer_wizard'][self.benefit_obj_key], self.benefit_obj_session_data)
self.assertJSONEqual(request.session['offer_wizard'][self.condition_form_kwargs_key], {
'data': {
- 'range': range_.pk,
+ 'range': None,
'type': '',
'value': None,
'custom_condition': str(condition.pk),
| When choosing a custom condition for your offer, it requires a range while it shouldn't
When you are choosing a custom condition on your offer, it will throw an error if you do not select a range as well.
<img width="752" alt="image" src="https://user-images.githubusercontent.com/7702200/156327295-b915ed75-48ea-4172-b1fb-98d8e67c674c.png">
However, the range is saved on the custom condition model so it should not be required.
### Steps to Reproduce
1. Create a custom condition, see [here](https://django-oscar.readthedocs.io/en/3.0.2/howto/how_to_create_a_custom_condition.html) how.
2. Create an offer and choose your custom condition without choosing a range, type and value.
3. Error should occur.
The logic in the the clean method of the ConditionForm seems wrong (line 127):
https://github.com/django-oscar/django-oscar/blob/23013a61a1f84517522c071bbeddb3fd3e841ee6/src/oscar/apps/dashboard/offers/forms.py#L126-L133
I think it should be like the BenefitForm does it:
https://github.com/django-oscar/django-oscar/blob/23013a61a1f84517522c071bbeddb3fd3e841ee6/src/oscar/apps/dashboard/offers/forms.py#L178-L191
Or is there any reason this is a requirement even when you choose a custom condition?
### Technical details
* Python version: Python 3.9.9
* Django version: Version: 3.2.9
* Oscar version: Version: 3.1
| I think you are right that the validation is wrong, and should be like the one on the `BenefitForm`.
Alright, I'll work on a fix then. | "2022-03-02T22:18:17Z" | 3.1 | [] | [
"tests/integration/dashboard/test_offer_forms.py::TestConditionForm::test_clean_custom_condition",
"tests/integration/dashboard/test_offer_forms.py::TestConditionForm::test_clean_custom_condition_with_range_type_and_value",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_condition_view_with_custom_condition_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_condition_view_with_custom_condition_type"
] | [
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_range_list_view",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_list_view",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_delete_view_for_voucher_offer_without_vouchers",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_offer_delete_view_for_voucher_offer_with_vouchers",
"tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_range_product_list_view",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_clean_new_incentive",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_clean_new_incentive_only_range",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_clean_no_value_data",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_clean_only_range_custom_exists",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_clean_validation_custom_exists",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_clean_validation_with_custom_benefit",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_init_with_custom_benefit",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_init_with_custom_benefit_with_instance",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_init_without_custom_benefit",
"tests/integration/dashboard/test_offer_forms.py::TestBenefitForm::test_is_valid_no_data",
"tests/integration/dashboard/test_offer_forms.py::TestConditionForm::test_clean_all_data",
"tests/integration/dashboard/test_offer_forms.py::TestConditionForm::test_clean_no_value",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_benefit_view_with_built_in_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_benefit_view_with_custom_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_condition_view_with_built_in_condition_type",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_meta_data_view",
"tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_restrictions_view",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_benefit_view_with_built_in_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_benefit_view_with_custom_benefit_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_condition_view_with_built_in_condition_type",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_meta_data_view",
"tests/integration/dashboard/test_offer_views.py::TestUpdateOfferWizardStepView::test_offer_restrictions_view"
] | 0a01977e9cef028bd3e8985309aa4741b6a8cb33 |
django-oscar/django-oscar | 3,884 | django-oscar__django-oscar-3884 | [
"3875"
] | 23013a61a1f84517522c071bbeddb3fd3e841ee6 | diff --git a/src/oscar/apps/partner/strategy.py b/src/oscar/apps/partner/strategy.py
--- a/src/oscar/apps/partner/strategy.py
+++ b/src/oscar/apps/partner/strategy.py
@@ -185,17 +185,19 @@ def parent_availability_policy(self, product, children_stock):
# Mixins - these can be used to construct the appropriate strategy class
-class UseFirstStockRecord(object):
+class UseFirstStockRecord:
"""
Stockrecord selection mixin for use with the ``Structured`` base strategy.
This mixin picks the first (normally only) stockrecord to fulfil a product.
-
- This is backwards compatible with Oscar<0.6 where only one stockrecord per
- product was permitted.
"""
def select_stockrecord(self, product):
- return product.stockrecords.first()
+ # We deliberately fetch by index here, to ensure that no additional database queries are made
+ # when stockrecords have already been prefetched in a queryset annotated using ProductQuerySet.base_queryset
+ try:
+ return product.stockrecords.all()[0]
+ except IndexError:
+ pass
class StockRequired(object):
| diff --git a/tests/integration/partner/test_selector_mixin.py b/tests/integration/partner/test_selector_mixin.py
--- a/tests/integration/partner/test_selector_mixin.py
+++ b/tests/integration/partner/test_selector_mixin.py
@@ -1,5 +1,6 @@
from django.test import TestCase
+from oscar.apps.catalogue.models import Product
from oscar.apps.partner import strategy
from oscar.test import factories
@@ -17,3 +18,12 @@ def test_selects_first_stockrecord_for_product(self):
def test_returns_none_when_no_stock_records(self):
self.assertIsNone(self.mixin.select_stockrecord(self.product))
+
+ def test_does_not_generate_additional_query_when_passed_product_from_base_queryset(self):
+ product = Product.objects.base_queryset().first()
+ # Regression test for https://github.com/django-oscar/django-oscar/issues/3875
+ # If passed a product from a queryset annotated by base_queryset, then
+ # the selector should not trigger any additional database queries because
+ # it should rely on the prefetched stock records.
+ with self.assertNumQueries(0):
+ self.mixin.select_stockrecord(product)
| Performance issue in cases where selecting strategy for product
Found a bug? Please fill out the sections below.
### Issue Summary
In Oscar 2.1, Selecting a strategy for product in [`UseFirstStockRecord`](https://github.com/django-oscar/django-oscar/blob/2.1.0b0/src/oscar/apps/partner/strategy.py#L188) used to (correctly, for performance reasons) index on the related stock records for a product to get the first. This meant, of course, that the `prefetch_related` call to `stockrecords` on `Product` was used and no additional queries generated.
Now, in Oscar 3.1 [this was changed to use the queryset's `first` method](https://github.com/django-oscar/django-oscar/blob/3.1/src/oscar/apps/partner/strategy.py#L188), which unfortunately makes the prefetch invalid and causes a new query each time a product shows price info (for various reasons, this has a huge performance impact on my use case).
This change was introduced in [this commit](https://github.com/django-oscar/django-oscar/commit/3a826796d01e5cba345aa646dbc5c8ae466cbf4a), which also implemented the same pattern over various related queries, and therefore I assume has similar performance implications (but I haven't checked).
### Steps to Reproduce
Try to render a page with various snippets of pricing info for a collection of hundreds of products - use a tool like Django Debug Toolbar to see the query multiplication :)
### Technical details
* Python version: Run `python --version`: 3.10
* Django version: Look in your requirements.txt, or run `pip show django | grep Version` 3.2.12
* Oscar version: Look in your requirements.txt, or run `pip show django-oscar | grep Version`. 3.1
| Interesting, I would have thought that the [0] indexing was done because queryset.first() didn't exist at the time this was written.
could you show us a screenshot of your usecase or add a url? I think it would be good to be able to replicate the scenario.
Hey @specialunderwear
I don't have a public URL but you can see the docs for `prefetch_related` that this is the expected behaviour (that the prefetch is redundant because we've chained a new clause to the query):
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related
The "note" section there clearly illustrates, using `.filter`, but the principle is the same as using `.first`, and easily observed by looking at the quanity of queries fired if one switches from using `.first` to `[0]`.
So, using `.first()` has negative performance implications with this change in Oscar - it means the optimization of prefetching the stock records is redundant, and that the query performance from that optimization is therefore no longer present).
Hah, this is interesting. I too had just assumed that this was legacy code that was written before `first()` was introduced. I think we need to revert the changes made to this query in commit, but also add docstrings explaining why it's done that way, as it's not immediately obvious. Having had a look at the whole commit through, I think it needs to be only partially reverted - other instances of using this pattern do just seem to be legacy code.
@solarissmoke
Yes, it is not obvious from the code, and a way to document it better would also be to emphasize where Oscar does `select_related` and `prefetch_related` queries - I assume there will be Oscar users who don't know the details of Django's ORM and won't be aware that any customization they may do to queries will make Oscar's use of `select_related` and `prefetch_related` redundant, impacting performance.
Also see the [docs](https://docs.djangoproject.com/en/4.0/ref/models/querysets/#first) and the [implementation](https://github.com/django/django/blob/main/django/db/models/query.py#L862) for `.first()` - Because of the stuff around ordering, I would be careful about using it in Oscar to be honest - `first()` and `all()[0]` are *not* guaranteed to return the same instance due to how ordering may or may not be implemented. | "2022-03-02T05:01:53Z" | 3.1 | [] | [
"tests/integration/partner/test_selector_mixin.py::TestUseFirstStockRecordMixin::test_does_not_generate_additional_query_when_passed_product_from_base_queryset"
] | [
"tests/integration/partner/test_selector_mixin.py::TestUseFirstStockRecordMixin::test_returns_none_when_no_stock_records",
"tests/integration/partner/test_selector_mixin.py::TestUseFirstStockRecordMixin::test_selects_first_stockrecord_for_product"
] | 0a01977e9cef028bd3e8985309aa4741b6a8cb33 |
django-oscar/django-oscar | 3,311 | django-oscar__django-oscar-3311 | [
"3308"
] | 9574ce2a56f3d99836c2e20785c116da12af6c42 | diff --git a/src/oscar/core/customisation.py b/src/oscar/core/customisation.py
--- a/src/oscar/core/customisation.py
+++ b/src/oscar/core/customisation.py
@@ -36,6 +36,11 @@ def subfolders(path):
def inherit_app_config(local_app_folder_path, local_app_name, app_config):
+ create_file(
+ join(local_app_folder_path, '__init__.py'),
+ "default_app_config = '{app_name}.apps.{app_config_class_name}'\n".format(
+ app_name=local_app_name,
+ app_config_class_name=app_config.__class__.__name__))
create_file(
join(local_app_folder_path, 'apps.py'),
"import {app_config_class_module} as apps\n\n\n"
| diff --git a/tests/__init__.py b/tests/__init__.py
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -15,3 +15,16 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
sys.path = self.original_paths
+
+
+def delete_from_import_cache(module_name):
+ """
+ Deletes imported modules from the cache, so that they do not interfere with
+ subsequent imports of different modules of the same names.
+
+ Useful in situations where dynamically-created files are imported.
+ """
+ parts = module_name.split('.')
+ for i, _ in enumerate(parts, 1):
+ submodule_name = '.'.join(parts[:i])
+ del sys.modules[submodule_name]
diff --git a/tests/integration/core/test_customisation.py b/tests/integration/core/test_customisation.py
--- a/tests/integration/core/test_customisation.py
+++ b/tests/integration/core/test_customisation.py
@@ -8,6 +8,7 @@
from django.test import TestCase, override_settings
from oscar.core import customisation
+from tests import delete_from_import_cache
VALID_FOLDER_PATH = 'tests/_site/apps'
@@ -39,12 +40,22 @@ def test_creates_new_folder(tmpdir):
path.join('order').ensure_dir()
-def test_creates_init_file(tmpdir):
+def test_creates_init_file(tmpdir, monkeypatch):
path = tmpdir.mkdir('fork')
customisation.fork_app('order', str(path), 'order')
path.join('order').join('__init__.py').ensure()
+ monkeypatch.syspath_prepend(str(tmpdir))
+
+ config_module = __import__('fork.order.apps', fromlist=['OrderConfig'])
+ delete_from_import_cache('fork.order.apps')
+
+ expected_string = "default_app_config = '{}.apps.OrderConfig".format(
+ config_module.OrderConfig.name)
+ contents = path.join('order').join('__init__.py').read()
+ assert expected_string in contents
+
def test_handles_dashboard_app(tmpdir):
# Dashboard apps are fiddly as they aren't identified by a single app
| Class loader throws an error after forking dashboard
## Issue Summary
Using a forked dashboard application results in an error.
## Steps to Reproduce
1. Set up an Oscar project named `foo` as described in the section titled "Building your own shop"
2. Run `./manage.py oscar_fork_app dashboard foo`
3. Substitute `foo.dashboard` for `oscar.apps.dashboard` in `foo/settings.py`
4. Run `./manage.py`
The following exception is thrown:
<pre>Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python3.8/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/lib/python3.8/site-packages/django/core/management/__init__.py", line 338, in execute
django.setup()
File "/usr/lib/python3.8/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 116, in populate
app_config.ready()
File "/usr/lib/python3.8/site-packages/oscar/apps/dashboard/reports/apps.py", line 16, in ready
self.index_view = get_class('dashboard.reports.views', 'IndexView')
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 31, in get_class
return get_classes(module_label, [classname], module_prefix)[0]
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 41, in get_classes
return class_loader(module_label, classnames, module_prefix)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 99, in default_class_loader
oscar_module = _import_module(oscar_module_label, classnames)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 133, in _import_module
return __import__(module_label, fromlist=classnames)
File "/usr/lib/python3.8/site-packages/oscar/apps/dashboard/reports/views.py", line 9, in <module>
ReportForm = get_class('dashboard.reports.forms', 'ReportForm')
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 31, in get_class
return get_classes(module_label, [classname], module_prefix)[0]
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 41, in get_classes
return class_loader(module_label, classnames, module_prefix)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 99, in default_class_loader
oscar_module = _import_module(oscar_module_label, classnames)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 133, in _import_module
return __import__(module_label, fromlist=classnames)
File "/usr/lib/python3.8/site-packages/oscar/apps/dashboard/reports/forms.py", line 7, in <module>
GeneratorRepository = get_class('dashboard.reports.utils',
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 31, in get_class
return get_classes(module_label, [classname], module_prefix)[0]
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 41, in get_classes
return class_loader(module_label, classnames, module_prefix)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 99, in default_class_loader
oscar_module = _import_module(oscar_module_label, classnames)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 133, in _import_module
return __import__(module_label, fromlist=classnames)
File "/usr/lib/python3.8/site-packages/oscar/apps/dashboard/reports/utils.py", line 3, in <module>
OrderReportGenerator = get_class('order.reports', 'OrderReportGenerator')
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 31, in get_class
return get_classes(module_label, [classname], module_prefix)[0]
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 41, in get_classes
return class_loader(module_label, classnames, module_prefix)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 99, in default_class_loader
oscar_module = _import_module(oscar_module_label, classnames)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 133, in _import_module
return __import__(module_label, fromlist=classnames)
File "/usr/lib/python3.8/site-packages/oscar/apps/order/reports.py", line 7, in <module>
ReportGenerator = get_class('dashboard.reports.reports', 'ReportGenerator')
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 31, in get_class
return get_classes(module_label, [classname], module_prefix)[0]
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 41, in get_classes
return class_loader(module_label, classnames, module_prefix)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 104, in default_class_loader
app_name = _find_registered_app_name(module_label)
File "/usr/lib/python3.8/site-packages/oscar/core/loading.py", line 188, in _find_registered_app_name
raise AppNotFoundError(
oscar.core.exceptions.AppNotFoundError: Couldn't find an Oscar app to import dashboard.reports.reports from
</pre>
## Technical Details
* Python version: 3.8.1
* Django version: 1.11.28
* Oscar version: 2.0.4
| I suspect this is because you haven't forked any of the dashboard's sub-apps? You need to fork at least one of those as well - e.g., you need `foo.dashboard.catalogue` to exist in addition to `foo.dashboard`.
I did some further investigation on this. Forking additional dashboard applications did not solve the problem, but using`foo.dashbord.apps.DashboardConfig` in `INSTALLED_APPS` or adding
`default_app_config = 'foo.dashbord.apps.DashboardConfig'` to `foo/dashboard/__init__.py` did the trick.
According to the section titled "Customising Oscar" in the documentation, using the module path should suffice. However, the current implementation of `oscar_fork_app` no longer sets `default_app_config`. Is there a good reason for not setting it?
I think this was probably just an oversight. The documentation has been updated on master to [use the explicit app config](https://github.com/django-oscar/django-oscar/blob/master/docs/source/topics/customisation.rst), will try and get that onto readthedocs soon.
Leaving this open as a reminder to look into the `default_app_config`. | "2020-02-28T06:57:22Z" | 2.0 | [] | [
"tests/integration/core/test_customisation.py::test_creates_init_file"
] | [
"tests/integration/core/test_customisation.py::TestUtilities::test_subfolder_extraction",
"tests/integration/core/test_customisation.py::test_raises_exception_for_nonexistant_app_label",
"tests/integration/core/test_customisation.py::test_raises_exception_if_app_has_already_been_forked",
"tests/integration/core/test_customisation.py::test_creates_new_folder",
"tests/integration/core/test_customisation.py::test_handles_dashboard_app",
"tests/integration/core/test_customisation.py::test_creates_models_and_admin_file",
"tests/integration/core/test_customisation.py::test_copies_in_migrations_when_needed",
"tests/integration/core/test_customisation.py::test_dashboard_app_config",
"tests/integration/core/test_customisation.py::TestForkApp::test_absolute_target_path",
"tests/integration/core/test_customisation.py::TestForkApp::test_fork_third_party",
"tests/integration/core/test_customisation.py::TestForkApp::test_local_folder"
] | 2429ad9e88e9a432dfa60aaca703d99860f85389 |
django-oscar/django-oscar | 3,572 | django-oscar__django-oscar-3572 | [
"3162"
] | a4d07e028454ce49a7753dd3b2a3bb898a238883 | diff --git a/src/oscar/apps/basket/utils.py b/src/oscar/apps/basket/utils.py
--- a/src/oscar/apps/basket/utils.py
+++ b/src/oscar/apps/basket/utils.py
@@ -143,7 +143,7 @@ def consumed(self, offer=None):
def consumers(self):
return [x for x in self._offers.values() if self.consumed(x)]
- def available(self, offer=None) -> int: # noqa (too complex (11))
+ def available(self, offer=None) -> int:
"""
check how many items are available for offer
@@ -186,8 +186,4 @@ def available(self, offer=None) -> int: # noqa (too complex (11))
if check and offer not in x.combined_offers:
return 0
- # respect max_affected_items
- if offer.benefit.max_affected_items:
- max_affected_items = min(offer.benefit.max_affected_items, max_affected_items)
-
return max_affected_items - self.consumed(offer)
diff --git a/src/oscar/apps/offer/benefits.py b/src/oscar/apps/offer/benefits.py
--- a/src/oscar/apps/offer/benefits.py
+++ b/src/oscar/apps/offer/benefits.py
@@ -67,6 +67,7 @@ def apply(self, basket, condition, offer, discount_percent=None,
max_affected_items = self._effective_max_affected_items()
affected_lines = []
for price, line in line_tuples:
+ affected_items += line.quantity_with_offer_discount(offer)
if affected_items >= max_affected_items:
break
if discount_amount_available == 0:
diff --git a/src/oscar/apps/offer/conditions.py b/src/oscar/apps/offer/conditions.py
--- a/src/oscar/apps/offer/conditions.py
+++ b/src/oscar/apps/offer/conditions.py
@@ -47,7 +47,7 @@ def is_satisfied(self, offer, basket):
num_matches = 0
for line in basket.all_lines():
if self.can_apply_condition(line):
- num_matches += line.quantity_without_offer_discount(None)
+ num_matches += line.quantity_without_offer_discount(offer)
if num_matches >= self.value:
return True
return False
| diff --git a/tests/integration/basket/test_utils.py b/tests/integration/basket/test_utils.py
--- a/tests/integration/basket/test_utils.py
+++ b/tests/integration/basket/test_utils.py
@@ -76,7 +76,7 @@ def test_available_with_offer(self):
offer1 = ConditionalOfferFactory(name='offer1', benefit=benefit)
lines = basket.all_lines()
assert lines[0].consumer.available(offer1) == 1
- assert lines[1].consumer.available(offer1) == 5
+ assert lines[1].consumer.available(offer1) == 10
def test_consumed_with_offer(self, filled_basket):
offer1 = ConditionalOfferFactory(name='offer1')
diff --git a/tests/integration/offer/test_condition.py b/tests/integration/offer/test_condition.py
--- a/tests/integration/offer/test_condition.py
+++ b/tests/integration/offer/test_condition.py
@@ -3,13 +3,17 @@
import pytest
from django.test import TestCase
+from django.utils.timezone import now
from oscar.apps.basket.models import Basket
-from oscar.apps.offer import custom, models
+from oscar.apps.offer import applicator, custom, models
+from oscar.core.loading import get_class
from oscar.test import factories
from oscar.test.basket import add_product
from tests._site.model_tests_app.models import BasketOwnerCalledBarry
+Selector = get_class('partner.strategy', 'Selector')
+
@pytest.fixture
def products_some():
@@ -329,3 +333,47 @@ def test_is_not_satisfied_by_non_match(self):
def test_is_satisfied_by_match(self):
self.basket.owner = factories.UserFactory(first_name="Barry")
assert self.offer.is_condition_satisfied(self.basket)
+
+
+class TestOffersWithCountCondition(TestCase):
+
+ def setUp(self):
+ super().setUp()
+
+ self.basket = factories.create_basket(empty=True)
+
+ # Create range and add one product to it.
+ rng = factories.RangeFactory(name='All products', includes_all_products=True)
+ self.product = factories.ProductFactory()
+ rng.add_product(self.product)
+
+ # Create a non-exclusive offer #1.
+ condition1 = factories.ConditionFactory(range=rng, value=D('1'))
+ benefit1 = factories.BenefitFactory(range=rng, value=D('10'))
+ self.offer1 = factories.ConditionalOfferFactory(
+ condition=condition1, benefit=benefit1, start_datetime=now(),
+ name='Test offer #1', exclusive=False,
+ )
+
+ # Create a non-exclusive offer #2.
+ condition2 = factories.ConditionFactory(range=rng, value=D('1'))
+ benefit2 = factories.BenefitFactory(range=rng, value=D('5'))
+ self.offer2 = factories.ConditionalOfferFactory(
+ condition=condition2, benefit=benefit2, start_datetime=now(),
+ name='Test offer #2', exclusive=False,
+ )
+
+ def add_product(self):
+ self.basket.add_product(self.product)
+ self.basket.strategy = Selector().strategy()
+ applicator.Applicator().apply(self.basket)
+
+ def assertOffersApplied(self, offers):
+ applied_offers = self.basket.applied_offers()
+ self.assertEqual(len(offers), len(applied_offers))
+ for offer in offers:
+ self.assertIn(offer.id, applied_offers, msg=offer)
+
+ def test_both_non_exclusive_offers_are_applied(self):
+ self.add_product()
+ self.assertOffersApplied([self.offer1, self.offer2])
| Exclusive with Count Condition not work anymore
# Issue Summary
I create 2 offers with count condition, **Both are not exclusive**, After oscar version 2.0, It seem like it just apply only 1 offers not apply both anymore
### Steps to Reproduce
1. Create 2 offers like this
![Screen Shot 2019-08-29 at 17 02 19](https://user-images.githubusercontent.com/8855366/63931190-01b7f080-ca7f-11e9-8e34-d93f01c3d102.png)
2. Only 1 offer apply
![Screen Shot 2019-08-29 at 17 06 09](https://user-images.githubusercontent.com/8855366/63931399-67a47800-ca7f-11e9-8989-988bd9cf5b05.png)
**Expected**
1. Should apply both offers if it does not exclusive.?
Note
I try to dig into the issue and compare the load, I found out that, in condition.py they are some changed about is_satisfied like this image below
<img width="1606" alt="Screen Shot 2019-08-29 at 17 08 11" src="https://user-images.githubusercontent.com/8855366/63931528-a6d2c900-ca7f-11e9-8f08-24e6a7966516.png">
When I reverse code back it work like a charm, Any idea why you guy change that?
### Technical details
* Python version: 3.6.8
* Django version: 1.11.5
* Oscar version: 2.0.1.
| Indeed, this was changed in https://github.com/django-oscar/django-oscar/commit/c1c61ef5c5112068fbaeadf5714423becec8ba25#diff-008132744b4a8f62da8f13ae6286db70R49-R50, but only for `CountCondition`, not for `CoverageCondition` and `ValueCondition`, so I think this was an error.
Or the reason could also be in the `Condition.can_apply_condition` method. As the author of the change, could you please suggest @pjstevns what was the motivation of the change?
Are there any news on this issue? Or could I help with something.
@bruecksen it needs someone to spend a bit of time working out a fix - if you have time to do so that would be appreciated. | "2020-11-13T16:05:50Z" | 3.0 | [] | [
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_available_with_offer",
"tests/integration/offer/test_condition.py::TestOffersWithCountCondition::test_both_non_exclusive_offers_are_applied"
] | [
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_no_offer",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_offer",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consume",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_exclusive_offer_1",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_exclusive_offer_2",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_by_application",
"tests/integration/basket/test_utils.py::TestLineOfferConsumer::test_consumed_with_combined_offer",
"tests/integration/offer/test_condition.py::TestCountCondition::test_description",
"tests/integration/offer/test_condition.py::TestCountCondition::test_is_not_satisfied_by_empty_basket",
"tests/integration/offer/test_condition.py::TestCountCondition::test_not_discountable_product_fails_condition",
"tests/integration/offer/test_condition.py::TestCountCondition::test_empty_basket_fails_partial_condition",
"tests/integration/offer/test_condition.py::TestCountCondition::test_smaller_quantity_basket_passes_partial_condition",
"tests/integration/offer/test_condition.py::TestCountCondition::test_smaller_quantity_basket_upsell_message",
"tests/integration/offer/test_condition.py::TestCountCondition::test_matching_quantity_basket_fails_partial_condition",
"tests/integration/offer/test_condition.py::TestCountCondition::test_matching_quantity_basket_passes_condition",
"tests/integration/offer/test_condition.py::TestCountCondition::test_greater_quantity_basket_passes_condition",
"tests/integration/offer/test_condition.py::TestCountCondition::test_consumption",
"tests/integration/offer/test_condition.py::TestCountCondition::test_is_satisfied_accounts_for_consumed_items",
"tests/integration/offer/test_condition.py::TestValueCondition::test_description",
"tests/integration/offer/test_condition.py::TestValueCondition::test_empty_basket_fails_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_empty_basket_fails_partial_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_less_value_basket_fails_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_not_discountable_item_fails_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_upsell_message",
"tests/integration/offer/test_condition.py::TestValueCondition::test_matching_basket_fails_partial_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_less_value_basket_passes_partial_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_matching_basket_passes_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_greater_than_basket_passes_condition",
"tests/integration/offer/test_condition.py::TestValueCondition::test_consumption",
"tests/integration/offer/test_condition.py::TestValueCondition::test_consumption_with_high_value_product",
"tests/integration/offer/test_condition.py::TestValueCondition::test_is_consumed_respects_quantity_consumed",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_empty_basket_fails",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_empty_basket_fails_partial_condition",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_single_item_fails",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_not_discountable_item_fails",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_single_item_passes_partial_condition",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_upsell_message",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_duplicate_item_fails",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_duplicate_item_passes_partial_condition",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_covering_items_pass",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_covering_items_fail_partial_condition",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_covering_items_are_consumed",
"tests/integration/offer/test_condition.py::TestCoverageCondition::test_consumed_items_checks_affected_items",
"tests/integration/offer/test_condition.py::TestConditionProxyModels::test_name_and_description",
"tests/integration/offer/test_condition.py::TestConditionProxyModels::test_proxy",
"tests/integration/offer/test_condition.py::TestCustomCondition::test_is_not_satisfied_by_non_match",
"tests/integration/offer/test_condition.py::TestCustomCondition::test_is_satisfied_by_match"
] | 04cd6a4fc750db9310147d96776f06fe289269bf |
django-oscar/django-oscar | 3,823 | django-oscar__django-oscar-3823 | [
"3785"
] | 7da350296abf970a6a329b7c7c9041a00026964d | diff --git a/src/oscar/apps/catalogue/abstract_models.py b/src/oscar/apps/catalogue/abstract_models.py
--- a/src/oscar/apps/catalogue/abstract_models.py
+++ b/src/oscar/apps/catalogue/abstract_models.py
@@ -870,6 +870,7 @@ class Meta:
ordering = ['code']
verbose_name = _('Product attribute')
verbose_name_plural = _('Product attributes')
+ unique_together = ('code', 'product_class')
@property
def is_option(self):
diff --git a/src/oscar/apps/catalogue/migrations/0024_remove_duplicate_attributes.py b/src/oscar/apps/catalogue/migrations/0024_remove_duplicate_attributes.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/catalogue/migrations/0024_remove_duplicate_attributes.py
@@ -0,0 +1,69 @@
+# Generated by Django 3.2.9 on 2022-01-25 19:01
+
+from django.db import migrations
+from django.db.models import CharField, Count, Value
+from django.db.models.functions import Concat
+
+def remove_duplicate_attributes(apps, schema_editor):
+ """
+ Removes duplicate attributes that have the same code and product class.
+ """
+ ProductAttribute = apps.get_model('catalogue', 'ProductAttribute')
+ ProductClass = apps.get_model("catalogue", "ProductClass")
+
+ # Instead of iterating over all attributes, we concat the code and product class pk
+ # with a "|" so we can find duplicate attributes in one query.
+ duplicate_attributes = ProductAttribute.objects.annotate(
+ code_and_product_class=Concat('code', Value('|'), 'product_class__pk', output_field=CharField())
+ ).values('code_and_product_class').annotate(
+ same_code_count=Count('code_and_product_class')
+ ).filter(same_code_count__gt=1)
+
+ for attribute in duplicate_attributes:
+ attribute_code, product_class_pk = attribute["code_and_product_class"].split("|")
+ product_class = ProductClass.objects.get(pk=product_class_pk)
+ attributes = ProductAttribute.objects.filter(
+ code=attribute_code,
+ product_class=product_class
+ )
+ used_attributes = attributes.filter(productattributevalue__isnull=False)
+ used_attribute_count = used_attributes.distinct().count()
+
+ # In most cases, the used attributes count will be one or zero as
+ # the dashboard will always show one attribute. If the used attribute
+ # count is one, we exclude this from attributes and remove the others.
+ # If it's zero, we pick the last created and delete others.
+ if used_attribute_count == 1:
+ attributes.exclude(pk=used_attributes.first().pk).delete()
+ continue
+ elif used_attribute_count == 0:
+ attributes.exclude(pk=attributes.last().pk).delete()
+ continue
+
+ # If we found multiple attributes that have values linked to them,
+ # we must move them to one attribute and then delete the others.
+ # We can only do this if the value_types are all the same!
+ ASSERTION_MESSAGE = """Duplicate attribute found with code: %s but different types!
+ You could fix this by renaming the duplicate codes or by matching all types to one
+ type and update the attribute values accordingly for their new type. After that you can
+ re-run the migration.""" % attribute_code
+ assert used_attributes.values("type").distinct().count() == 1, ASSERTION_MESSAGE
+
+ # Choose one attribute that will be used to move to and others to be deleted.
+ to_be_used_attribute = used_attributes.first()
+ to_be_deleted_attributes = used_attributes.exclude(pk=to_be_used_attribute.pk)
+ for attribute in to_be_deleted_attributes:
+ attribute.productattributevalue_set.all().update(attribute=to_be_used_attribute)
+ attribute.delete()
+
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('catalogue', '0023_auto_20210824_1414'),
+ ]
+
+ operations = [
+ migrations.RunPython(remove_duplicate_attributes, migrations.RunPython.noop)
+ ]
diff --git a/src/oscar/apps/catalogue/migrations/0025_attribute_code_uniquetogether_constraint.py b/src/oscar/apps/catalogue/migrations/0025_attribute_code_uniquetogether_constraint.py
new file mode 100644
--- /dev/null
+++ b/src/oscar/apps/catalogue/migrations/0025_attribute_code_uniquetogether_constraint.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.9 on 2022-01-25 20:17
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('catalogue', '0024_remove_duplicate_attributes'),
+ ]
+
+ operations = [
+ migrations.AlterUniqueTogether(
+ name='productattribute',
+ unique_together={('code', 'product_class')},
+ ),
+ ]
| diff --git a/tests/integration/catalogue/test_attributes.py b/tests/integration/catalogue/test_attributes.py
--- a/tests/integration/catalogue/test_attributes.py
+++ b/tests/integration/catalogue/test_attributes.py
@@ -4,7 +4,7 @@
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
-from oscar.apps.catalogue.models import Product, ProductAttribute
+from oscar.apps.catalogue.models import Product, ProductAttribute, ProductClass
from oscar.test import factories
@@ -44,6 +44,17 @@ def test_attributes_refresh(self):
product.attr.refresh()
assert product.attr.a1 == "v2"
+ def test_attribute_code_uniquenesss(self):
+ product_class = factories.ProductClassFactory()
+ attribute1 = ProductAttribute.objects.create(name='a1', code='a1', product_class=product_class)
+ attribute1.full_clean()
+ attribute2 = ProductAttribute.objects.create(name='a1', code='a1', product_class=product_class)
+ with self.assertRaises(ValidationError):
+ attribute2.full_clean()
+ another_product_class = ProductClass.objects.create(name="another product class")
+ attribute3 = ProductAttribute.objects.create(name='a1', code='a1', product_class=another_product_class)
+ attribute3.full_clean()
+
class TestBooleanAttributes(TestCase):
| ProductAttribute.code should be a unique field
### Issue Summary
The product attribute should have a unique code.
You can only assign one attribute with that code in the dashboard-product anyway.
### Steps to Reproduce
1. In dashboard, go to `product-type` - `product attributes` page: _/dashboard/catalogue/product-type/1/update/_
2. Add two product attributes with the same name. (I use name att1 and type text.)
3. Save the form. Both attributes with the same code are saved and shown on the page.
4. Go to one `dashboard/products` page for that product class, _/dashboard/catalogue/products/8/?upc=&title=shirt_, only one attribute name is shown on the form.
5. Note that even I create attributes with different types, only one attribute of that code will be shown on the `dashboard/products` page.
![Screen Shot 2021-10-14 at 11 30 32 AM](https://user-images.githubusercontent.com/11536831/137376274-b0b32263-f2cd-492e-bbef-dcd8fedfa802.png)
![Screen Shot 2021-10-14 at 11 30 14 AM](https://user-images.githubusercontent.com/11536831/137376244-875b59c7-7ced-40b4-b4da-690479c8ea0e.png)
#### Expected result:
* Give Exception when saving the attribute - "Duplicate product attributes code / attributes with this code already exists."
* Enforce the `uniqueness` of `AbstractProductAttribute.code`. This is a SlugField.
* Another way is to enforce the unique_together of (code, type), while the data retrieval part needs to be updated as well.
* I can work on the PR for this issue, please let me know.
#### Cause
Here have the assumption that `attribute.code` should be unique.
```python
File: src/oscar/apps/dashboard/catalogue/forms.py
def set_initial_attribute_values(self, product_class, kwargs):
...
for attribute in product_class.attributes.all():
try:
value = instance.attribute_values.get(
attribute=attribute).value
except exceptions.ObjectDoesNotExist:
pass
else:
kwargs['initial']['attr_%s' % attribute.code] = value
```
### Technical details
* Python version: 3.9.7
* Django version: 3.2.7
* Oscar version: master
| We cannot globally enforce uniqueness of attribute codes, because Oscar permits reusing the same attribute code on different product types (and this can be useful to be able to do). I think the solution here would be to add validation on the formset for any given product class, to ensure that a code isn't repeated for that product class. PR welcome for this - note that it will be a bit messy to properly handle validation of deleted rows etc.
> We cannot globally enforce uniqueness of attribute codes, because Oscar permits reusing the same attribute code on different product types (and this can be useful to be able to do). I think the solution here would be to add validation on the formset for any given product class, to ensure that a code isn't repeated for that product class. PR welcome for this - note that it will be a bit messy to properly handle validation of deleted rows etc.
Can't we just add`unique_together = ('code', 'product_class',)` on the ProductAttribute model?
No, for the reason I mentioned in my comment: Oscar permits reusing the same attribute code on different product types. Imagine you have 20 product types which all share one attribute - Oscar currently allows that and it is (from my experience) a common use case.
Not sure if I'm misunderstanding you, but I understand the reusing the same attribute code on multiple product types is common. However, if you add `unique_together = ('code', 'product_class',)` on the ProductAttribute model's Meta class, it prevents you from using the same code for the product type you're editing. You can still use the same code on other product types.
My apologies, you're right and I misunderstood - `unique_together` as you describe would work. | "2021-12-07T19:44:05Z" | 3.1 | [] | [
"tests/integration/catalogue/test_attributes.py::TestContainer::test_attribute_code_uniquenesss"
] | [
"tests/integration/catalogue/test_attributes.py::TestContainer::test_attributes_initialised_before_write",
"tests/integration/catalogue/test_attributes.py::TestContainer::test_attributes_refresh",
"tests/integration/catalogue/test_attributes.py::TestBooleanAttributes::test_validate_boolean_values",
"tests/integration/catalogue/test_attributes.py::TestBooleanAttributes::test_validate_invalid_boolean_values",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_delete_multi_option_value",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_multi_option_value_as_text",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_save_multi_option_value",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_validate_invalid_multi_option_values",
"tests/integration/catalogue/test_attributes.py::TestMultiOptionAttributes::test_validate_multi_option_values",
"tests/integration/catalogue/test_attributes.py::TestOptionAttributes::test_option_value_as_text",
"tests/integration/catalogue/test_attributes.py::TestDatetimeAttributes::test_validate_datetime_values",
"tests/integration/catalogue/test_attributes.py::TestDatetimeAttributes::test_validate_invalid_datetime_values",
"tests/integration/catalogue/test_attributes.py::TestDateAttributes::test_validate_date_values",
"tests/integration/catalogue/test_attributes.py::TestDateAttributes::test_validate_datetime_values",
"tests/integration/catalogue/test_attributes.py::TestDateAttributes::test_validate_invalid_date_values",
"tests/integration/catalogue/test_attributes.py::TestIntegerAttributes::test_validate_integer_values",
"tests/integration/catalogue/test_attributes.py::TestIntegerAttributes::test_validate_invalid_integer_values",
"tests/integration/catalogue/test_attributes.py::TestIntegerAttributes::test_validate_str_integer_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_float_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_integer_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_invalid_float_values",
"tests/integration/catalogue/test_attributes.py::TestFloatAttributes::test_validate_str_float_values",
"tests/integration/catalogue/test_attributes.py::TestTextAttributes::test_validate_invalid_float_values",
"tests/integration/catalogue/test_attributes.py::TestTextAttributes::test_validate_string_and_unicode_values",
"tests/integration/catalogue/test_attributes.py::TestFileAttributes::test_validate_file_values"
] | 0a01977e9cef028bd3e8985309aa4741b6a8cb33 |
django-oscar/django-oscar | 3,398 | django-oscar__django-oscar-3398 | [
"3397"
] | 0a3f300fdd27e93f5b25a22a58b87eb34287f989 | diff --git a/src/oscar/apps/basket/forms.py b/src/oscar/apps/basket/forms.py
--- a/src/oscar/apps/basket/forms.py
+++ b/src/oscar/apps/basket/forms.py
@@ -148,7 +148,7 @@ def _create_parent_product_fields(self, product):
"""
choices = []
disabled_values = []
- for child in product.children.all():
+ for child in product.children.public():
# Build a description of the child, including any pertinent
# attributes
attr_summary = child.attribute_summary
diff --git a/src/oscar/apps/catalogue/managers.py b/src/oscar/apps/catalogue/managers.py
--- a/src/oscar/apps/catalogue/managers.py
+++ b/src/oscar/apps/catalogue/managers.py
@@ -107,6 +107,12 @@ def browsable(self):
"""
return self.filter(parent=None, is_public=True)
+ def public(self):
+ """
+ Excludes non-public products
+ """
+ return self.filter(is_public=True)
+
def browsable_dashboard(self):
"""
Products that should be browsable in the dashboard.
diff --git a/src/oscar/apps/partner/strategy.py b/src/oscar/apps/partner/strategy.py
--- a/src/oscar/apps/partner/strategy.py
+++ b/src/oscar/apps/partner/strategy.py
@@ -150,7 +150,7 @@ def select_children_stockrecords(self, product):
Select appropriate stock record for all children of a product
"""
records = []
- for child in product.children.all():
+ for child in product.children.public():
# Use tuples of (child product, stockrecord)
records.append((child, self.select_stockrecord(child)))
return records
| diff --git a/tests/unit/catalogue/test_managers.py b/tests/unit/catalogue/test_managers.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/catalogue/test_managers.py
@@ -0,0 +1,11 @@
+import pytest
+
+from oscar.apps.catalogue.models import Product
+from oscar.test.factories import ProductFactory
+
+
+@pytest.mark.django_db
+def test_public_queryset_method_filters():
+ ProductFactory(is_public=True)
+ ProductFactory(is_public=False)
+ assert Product.objects.public().count() == 1
| is_public flag is not respected when listing child products
### Issue Summary
When rendering product variants (e.g., in the detail view for a parent product), Oscar does not check whether those variants are public. It uses `product.children.all`.
### Steps to Reproduce
1. Set `is_public=False` on a child product!
2. Notice that it is still listed in the parent product detail view.
| "2020-06-10T11:31:57Z" | 2.1 | [] | [
"tests/unit/catalogue/test_managers.py::test_public_queryset_method_filters"
] | [] | 226b173bf1b9b36bcabe5bae6bd06cff3013a20c |