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:41"
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:25"
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:23"
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:05"
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:13"
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\n-(...TRUNCATED)
"diff --git a/tests/integration/basket/test_utils.py b/tests/integration/basket/test_utils.py\n--- a(...TRUNCATED)
"Offer Tracking for Stacked Offers\nI was testing out the stacked offer tracking that will be includ(...TRUNCATED)
"I'll take a look at this asap.\r\n\r\nThe LineOfferConsumer interface could do with more extensive (...TRUNCATED)
"2020-08-28T09:12:41"
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/inte(...TRUNCATED)
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\n-(...TRUNCATED)
"diff --git a/tests/integration/dashboard/test_offer_views.py b/tests/integration/dashboard/test_off(...TRUNCATED)
"Benefit.proxy_class and Condition.proxy_class fields gets overridden if a new offer with a custom c(...TRUNCATED)
"@jwayodi is it possible to fix this in #3632? To reproduce on the sandbox:\r\n\r\n1. Start creating(...TRUNCATED)
"2021-03-16T06:13:01"
3.0
[]
["tests/integration/dashboard/test_offer_views.py::TestCreateOfferWizardStepView::test_offer_benefit(...TRUNCATED)
["tests/integration/dashboard/test_offer_views.py::TestDashboardOffers::test_range_list_view","tests(...TRUNCATED)
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(...TRUNCATED)
"diff --git a/tests/integration/catalogue/test_attributes.py b/tests/integration/catalogue/test_attr(...TRUNCATED)
"Writing to products attributes with Product.attr can lead to dataloss\n### Issue Summary\r\n\r\nWri(...TRUNCATED)
"As a workaround, before writing, just call\r\n```\r\np.attr.initiate_attributes()\r\n```\n@specialu(...TRUNCATED)
"2020-09-10T12:07:35"
2.1
[]
["tests/integration/catalogue/test_attributes.py::TestContainer::test_attributes_initialised_before_(...TRUNCATED)
["tests/integration/catalogue/test_attributes.py::TestBooleanAttributes::test_validate_boolean_value(...TRUNCATED)
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(...TRUNCATED)
"diff --git a/tests/_site/apps/catalogue/migrations/0021_auto_20201005_0844.py b/tests/_site/apps/ca(...TRUNCATED)
"Add SEO fields to product and category models and make editable in the dashboard\nThere are a few S(...TRUNCATED)
"Hey @solarissmoke ,\r\nJust wanted to confirm that we are talking about the `AbtractProduct` and `A(...TRUNCATED)
"2020-10-05T08:34:15"
2.1
[]
["tests/unit/catalogue/test_models.py::ProductTestCase::test_get_meta_description","tests/unit/catal(...TRUNCATED)
[]
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\(...TRUNCATED)
"diff --git a/tests/integration/address/test_models.py b/tests/integration/address/test_models.py\n-(...TRUNCATED)
"The postal Code validation for Israel should also take 5 digit numbers\nIn oscar.apps.address.abstr(...TRUNCATED)
"Right, but seems 5-digit postal codes are not officially used any more, could you please mention wo(...TRUNCATED)
"2020-09-08T10:09:09"
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_whites(...TRUNCATED)
226b173bf1b9b36bcabe5bae6bd06cff3013a20c
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
58
Edit dataset card