Fixed #108 -- Removed the restrictions system

This commit is contained in:
Raphael Michel
2015-12-06 17:49:02 +01:00
parent b26eaaa6c9
commit 4a1122a862
25 changed files with 26 additions and 1256 deletions

View File

@@ -1,24 +0,0 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from pretix import __version__ as version
from pretix.base.plugins import PluginType
class TimeRestrictionApp(AppConfig):
name = 'pretix.plugins.timerestriction'
verbose_name = _("Time restriction")
class PretixPluginMeta:
type = PluginType.RESTRICTION
name = _("Restriction by time")
author = _("the pretix team")
version = version
description = _("This plugin adds the possibility to restrict the sale " +
"of a given product or variation to a certain timeframe " +
"or change its price during a certain period.")
def ready(self):
from . import signals # NOQA
default_app_config = 'pretix.plugins.timerestriction.TimeRestrictionApp'

View File

@@ -1,38 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import versions.models
from django.db import migrations, models
import pretix.base.models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '__first__'),
]
operations = [
migrations.CreateModel(
name='TimeRestriction',
fields=[
('id', models.CharField(serialize=False, max_length=36, primary_key=True)),
('identity', models.CharField(max_length=36)),
('version_start_date', models.DateTimeField()),
('version_end_date', models.DateTimeField(null=True, blank=True, default=None)),
('version_birth_date', models.DateTimeField()),
('timeframe_from', models.DateTimeField(verbose_name='Start of time frame')),
('timeframe_to', models.DateTimeField(verbose_name='End of time frame')),
('price', models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True, verbose_name='Price in time frame')),
('event', versions.models.VersionedForeignKey(verbose_name='Event', to='pretixbase.Event', related_name='restrictions_timerestriction_timerestriction')),
('item', versions.models.VersionedForeignKey(related_name='restrictions_timerestriction_timerestriction', null=True, verbose_name='Item', to='pretixbase.Item', blank=True)),
('variations', pretix.base.models.VariationsField(related_name='restrictions_timerestriction_timerestriction', blank=True, to='pretixbase.ItemVariation', verbose_name='Variations')),
],
options={
'verbose_name_plural': 'Restrictions',
'abstract': False,
'verbose_name': 'Restriction',
},
),
]

View File

@@ -1,24 +0,0 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
from pretix.base.models import BaseRestriction
class TimeRestriction(BaseRestriction):
"""
This restriction makes an item or variation only available
within a given time frame. The price of the item can be modified
during this time frame.
"""
timeframe_from = models.DateTimeField(
verbose_name=_("Start of time frame"),
)
timeframe_to = models.DateTimeField(
verbose_name=_("End of time frame"),
)
price = models.DecimalField(
null=True, blank=True,
max_digits=7, decimal_places=2,
verbose_name=_("Price in time frame"),
)

View File

@@ -1,154 +0,0 @@
from django.dispatch import receiver
from django.forms.models import inlineformset_factory
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from pretix.base.models import Item
from pretix.base.signals import determine_availability
from pretix.control.forms import RestrictionForm, RestrictionInlineFormset
from pretix.control.signals import restriction_formset
from .models import TimeRestriction
# The maximum validity of our cached values is the next date, one of our
# timeframe_from or tiemframe_to actions happens
def timediff(restrictions):
for r in restrictions:
if r.timeframe_from >= now():
yield (r.timeframe_from - now()).total_seconds()
if r.timeframe_to >= now():
yield (r.timeframe_to - now()).total_seconds()
@receiver(determine_availability, dispatch_uid="restriction_time")
def availability_handler(sender, **kwargs):
# Handle the signal's input arguments
item = kwargs['item']
variations = kwargs['variations']
cache = kwargs['cache']
context = kwargs['context'] # NOQA
# Fetch all restriction objects applied to this item
restrictions = list(TimeRestriction.objects.current.filter(
item=item,
).prefetch_related('variations'))
# If we do not know anything about this item, we are done here.
if len(restrictions) == 0:
return variations
# IMPORTANT:
# We need to make a two-level deep copy of the variations list before we
# modify it, becuase we need to to copy the dictionaries. Otherwise, we'll
# interfere with other plugins.
variations = [d.copy() for d in variations]
try:
cache_validity = min(timediff(restrictions))
except ValueError:
# empty sequence
# If we get here, there are restrictions available but nothing will
# change about them any more. If it were not for the case of no
# restriction for the base item but restrictions for special
# variations, we could quit here with 'item not available'.
cache_validity = 3600
# Walk through all variations we are asked for
for v in variations:
var_restrictions = []
for restriction in restrictions:
applied_to = list(restriction.variations.current.all())
# Only take this restriction into consideration if it
# is directly applied to this variation or if the item
# has no variations
if v.empty() or ('variation' in v and v['variation'] in applied_to):
var_restrictions.append(restriction)
if not var_restrictions:
v['available'] = True
v['price'] = None
continue
# If this point is reached, there ARE time restrictions for this item
# Therefore, it is only available inside one of the timeframes, but not
# without any timeframe.
available = False
# Make up some unique key for this variation
cachekey = 'timerestriction:%s:%s' % (
item.identity,
v.identify(),
)
# Fetch from cache, if available
cached = cache.get(cachekey)
if cached is not None:
v['available'] = (cached.split(":")[0] == 'True')
try:
v['price'] = float(cached.split(":")[1])
except ValueError:
v['price'] = None
continue
# Walk through all restriction objects applied to this item
prices = []
for restriction in var_restrictions:
if restriction.timeframe_from <= now() <= restriction.timeframe_to:
# Selling this item is currently possible
available = True
prices.append(restriction.price)
# Use the lowest of all prices set by restrictions
prices = [p for p in prices if p is not None]
price = min(prices) if prices else None
v['available'] = available
v['price'] = price
cache.set(
cachekey,
'%s:%s' % (
'True' if available else 'False',
str(price) if price else ''
),
cache_validity
)
return variations
class TimeRestrictionForm(RestrictionForm):
class Meta:
model = TimeRestriction
localized_fields = '__all__'
fields = [
'variations',
'timeframe_from',
'timeframe_to',
'price',
]
@receiver(restriction_formset, dispatch_uid="restriction_time_formset")
def formset_handler(sender, **kwargs):
formset = inlineformset_factory(
Item,
TimeRestriction,
formset=RestrictionInlineFormset,
form=TimeRestrictionForm,
can_order=False,
can_delete=True,
extra=0,
)
return {
'title': _('Restriction by time'),
'formsetclass': formset,
'prefix': 'timerestriction',
'description': 'If you use this restriction type, the system will only sell variations which are covered '
'by at least one of the timeframes you define below. You can also change the price of '
'variations for within the given timeframe. Please note, that if you change the price of '
'variations here, this will overrule the price set in the "Variations" section.'
}