Changeset - 87e6fa064a11
[Not reviewed]
Merge
1 7 3
Christopher Neugebauer - 8 years ago 2016-04-12 01:39:54
chrisjrn@gmail.com
Merge branch 'master' into admin_models_cleanup
9 files changed with 286 insertions and 143 deletions:
0 comments (0 inline, 0 general)
registrasion/admin.py
Show inline comments
...
 
@@ -96,14 +96,14 @@ class VoucherDiscountInline(nested_admin.NestedStackedInline):
 
    inlines = [
 
        DiscountForProductInline,
 
        DiscountForCategoryInline,
 
    ]
 

	
 

	
 
class VoucherEnablingConditionInline(nested_admin.NestedStackedInline):
 
    model = rego.VoucherEnablingCondition
 
class VoucherFlagInline(nested_admin.NestedStackedInline):
 
    model = rego.VoucherFlag
 
    verbose_name = _("Product and category enabled by voucher")
 
    verbose_name_plural = _("Products and categories enabled by voucher")
 

	
 
    # TODO work out why we're allowed to add more than one?
 
    max_num = 1
 
    extra = 1
...
 
@@ -119,13 +119,13 @@ class VoucherAdmin(nested_admin.NestedAdmin):
 
        try:
 
            discount_effects = obj.voucherdiscount.effects()
 
        except ObjectDoesNotExist:
 
            discount_effects = None
 

	
 
        try:
 
            enabling_effects = obj.voucherenablingcondition.effects()
 
            enabling_effects = obj.voucherflag.effects()
 
        except ObjectDoesNotExist:
 
            enabling_effects = None
 

	
 
        if discount_effects:
 
            out.append("Discounts: " + str(list(discount_effects)))
 
        if enabling_effects:
...
 
@@ -134,52 +134,52 @@ class VoucherAdmin(nested_admin.NestedAdmin):
 
        return "\n".join(out)
 

	
 
    model = rego.Voucher
 
    list_display = ("recipient", "code", "effects")
 
    inlines = [
 
        VoucherDiscountInline,
 
        VoucherEnablingConditionInline,
 
        VoucherFlagInline,
 
    ]
 

	
 

	
 
# Enabling conditions
 
@admin.register(rego.ProductEnablingCondition)
 
class ProductEnablingConditionAdmin(
 
@admin.register(rego.ProductFlag)
 
class ProductFlagAdmin(
 
        nested_admin.NestedAdmin,
 
        EffectsDisplayMixin):
 

	
 
    def enablers(self, obj):
 
        return list(obj.enabling_products.all())
 

	
 
    model = rego.ProductEnablingCondition
 
    model = rego.ProductFlag
 
    fields = ("description", "enabling_products", "mandatory", "products",
 
              "categories"),
 

	
 
    list_display = ("description", "enablers", "effects")
 

	
 

	
 
# Enabling conditions
 
@admin.register(rego.CategoryEnablingCondition)
 
class CategoryEnablingConditionAdmin(
 
@admin.register(rego.CategoryFlag)
 
class CategoryFlagAdmin(
 
        nested_admin.NestedAdmin,
 
        EffectsDisplayMixin):
 

	
 
    model = rego.CategoryEnablingCondition
 
    model = rego.CategoryFlag
 
    fields = ("description", "enabling_category", "mandatory", "products",
 
              "categories"),
 

	
 
    list_display = ("description", "enabling_category", "effects")
 
    ordering = ("enabling_category",)
 

	
 

	
 
# Enabling conditions
 
@admin.register(rego.TimeOrStockLimitEnablingCondition)
 
class TimeOrStockLimitEnablingConditionAdmin(
 
@admin.register(rego.TimeOrStockLimitFlag)
 
class TimeOrStockLimitFlagAdmin(
 
        nested_admin.NestedAdmin,
 
        EffectsDisplayMixin):
 
    model = rego.TimeOrStockLimitEnablingCondition
 
    model = rego.TimeOrStockLimitFlag
 

	
 
    list_display = (
 
        "description",
 
        "start_time",
 
        "end_time",
 
        "limit",
registrasion/controllers/cart.py
Show inline comments
...
 
@@ -115,13 +115,13 @@ class CartController(object):
 
        items_in_cart.filter(quantity=0).delete()
 

	
 
        self.end_batch()
 

	
 
    def _test_limits(self, product_quantities):
 
        ''' Tests that the quantity changes we intend to make do not violate
 
        the limits and enabling conditions imposed on the products. '''
 
        the limits and flag conditions imposed on the products. '''
 

	
 
        errors = []
 

	
 
        # Test each product limit here
 
        for product, quantity in product_quantities:
 
            if quantity < 0:
...
 
@@ -156,14 +156,14 @@ class CartController(object):
 
                    category,
 
                    "You may only have %d items in category: %s" % (
 
                        limit, category.name,
 
                    )
 
                ))
 

	
 
        # Test the enabling conditions
 
        errs = ConditionController.test_enabling_conditions(
 
        # Test the flag conditions
 
        errs = ConditionController.test_flags(
 
            self.cart.user,
 
            product_quantities=product_quantities,
 
        )
 

	
 
        if errs:
 
            for error in errs:
registrasion/controllers/conditions.py
Show inline comments
...
 
@@ -17,30 +17,30 @@ ConditionAndRemainder = namedtuple(
 
        "remainder",
 
    ),
 
)
 

	
 

	
 
class ConditionController(object):
 
    ''' Base class for testing conditions that activate EnablingCondition
 
    ''' Base class for testing conditions that activate Flag
 
    or Discount objects. '''
 

	
 
    def __init__(self):
 
        pass
 

	
 
    @staticmethod
 
    def for_condition(condition):
 
        CONTROLLERS = {
 
            rego.CategoryEnablingCondition: CategoryConditionController,
 
            rego.CategoryFlag: CategoryConditionController,
 
            rego.IncludedProductDiscount: ProductConditionController,
 
            rego.ProductEnablingCondition: ProductConditionController,
 
            rego.ProductFlag: ProductConditionController,
 
            rego.TimeOrStockLimitDiscount:
 
                TimeOrStockLimitDiscountController,
 
            rego.TimeOrStockLimitEnablingCondition:
 
                TimeOrStockLimitEnablingConditionController,
 
            rego.TimeOrStockLimitFlag:
 
                TimeOrStockLimitFlagController,
 
            rego.VoucherDiscount: VoucherConditionController,
 
            rego.VoucherEnablingCondition: VoucherConditionController,
 
            rego.VoucherFlag: VoucherConditionController,
 
        }
 

	
 
        try:
 
            return CONTROLLERS[type(condition)](condition)
 
        except KeyError:
 
            return ConditionController()
...
 
@@ -62,22 +62,22 @@ class ConditionController(object):
 
            PLURAL:
 
                "Only %(remainder)d of the following items remain: %(items)s"
 
        },
 
    }
 

	
 
    @classmethod
 
    def test_enabling_conditions(
 
    def test_flags(
 
            cls, user, products=None, product_quantities=None):
 
        ''' Evaluates all of the enabling conditions on the given products.
 
        ''' Evaluates all of the flag conditions on the given products.
 

	
 
        If `product_quantities` is supplied, the condition is only met if it
 
        will permit the sum of the product quantities for all of the products
 
        it covers. Otherwise, it will be met if at least one item can be
 
        accepted.
 

	
 
        If all enabling conditions pass, an empty list is returned, otherwise
 
        If all flag conditions pass, an empty list is returned, otherwise
 
        a list is returned containing all of the products that are *not
 
        enabled*. '''
 

	
 
        if products is not None and product_quantities is not None:
 
            raise ValueError("Please specify only products or "
 
                             "product_quantities")
...
 
@@ -87,34 +87,33 @@ class ConditionController(object):
 
                              for product, quantity in product_quantities)
 
        elif product_quantities is None:
 
            products = set(products)
 
            quantities = {}
 

	
 
        # Get the conditions covered by the products themselves
 

	
 
        prods = (
 
            product.enablingconditionbase_set.select_subclasses()
 
            product.flagbase_set.select_subclasses()
 
            for product in products
 
        )
 
        # Get the conditions covered by their categories
 
        cats = (
 
            category.enablingconditionbase_set.select_subclasses()
 
            category.flagbase_set.select_subclasses()
 
            for category in set(product.category for product in products)
 
        )
 

	
 
        if products:
 
            # Simplify the query.
 
            all_conditions = reduce(operator.or_, itertools.chain(prods, cats))
 
        else:
 
            all_conditions = []
 

	
 
        # All mandatory conditions on a product need to be met
 
        mandatory = defaultdict(lambda: True)
 
        # At least one non-mandatory condition on a product must be met
 
        # if there are no mandatory conditions
 
        non_mandatory = defaultdict(lambda: False)
 
        # All disable-if-false conditions on a product need to be met
 
        do_not_disable = defaultdict(lambda: True)
 
        # At least one enable-if-true condition on a product must be met
 
        do_enable = defaultdict(lambda: False)
 
        # (if either sort of condition is present)
 

	
 
        messages = {}
 

	
 
        for condition in all_conditions:
 
            cond = cls.for_condition(condition)
 
            remainder = cond.user_quantity_remaining(user)
...
 
@@ -143,48 +142,49 @@ class ConditionController(object):
 
            if not met:
 
                items = ", ".join(str(product) for product in all_products)
 
                base = cls.MESSAGE[remainder == 0][len(all_products) == 1]
 
                message = base % {"items": items, "remainder": remainder}
 

	
 
            for product in all_products:
 
                if condition.mandatory:
 
                    mandatory[product] &= met
 
                if condition.is_disable_if_false:
 
                    do_not_disable[product] &= met
 
                else:
 
                    non_mandatory[product] |= met
 
                    do_enable[product] |= met
 

	
 
                if not met and product not in messages:
 
                    messages[product] = message
 

	
 
        valid = defaultdict(lambda: True)
 
        for product in itertools.chain(mandatory, non_mandatory):
 
            if product in mandatory:
 
                # If there's a mandatory condition, all must be met
 
                valid[product] = mandatory[product]
 
            else:
 
                # Otherwise, we need just one non-mandatory condition met
 
                valid[product] = non_mandatory[product]
 
        valid = {}
 
        for product in itertools.chain(do_not_disable, do_enable):
 
            if product in do_enable:
 
                # If there's an enable-if-true, we need need of those met too.
 
                # (do_not_disable will default to true otherwise)
 
                valid[product] = do_not_disable[product] and do_enable[product]
 
            elif product in do_not_disable:
 
                # If there's a disable-if-false condition, all must be met
 
                valid[product] = do_not_disable[product]
 

	
 
        error_fields = [
 
            (product, messages[product])
 
            for product in valid if not valid[product]
 
        ]
 

	
 
        return error_fields
 

	
 
    def user_quantity_remaining(self, user):
 
        ''' Returns the number of items covered by this enabling condition the
 
        ''' Returns the number of items covered by this flag condition the
 
        user can add to the current cart. This default implementation returns
 
        a big number if is_met() is true, otherwise 0.
 

	
 
        Either this method, or is_met() must be overridden in subclasses.
 
        '''
 

	
 
        return 99999999 if self.is_met(user) else 0
 

	
 
    def is_met(self, user):
 
        ''' Returns True if this enabling condition is met, otherwise returns
 
        ''' Returns True if this flag condition is met, otherwise returns
 
        False.
 

	
 
        Either this method, or user_quantity_remaining() must be overridden
 
        in subclasses.
 
        '''
 
        return self.user_quantity_remaining(user) > 0
...
 
@@ -208,13 +208,13 @@ class CategoryConditionController(ConditionController):
 
            product__in=enabling_products,
 
        ).count()
 
        return products_count > 0
 

	
 

	
 
class ProductConditionController(ConditionController):
 
    ''' Condition tests for ProductEnablingCondition and
 
    ''' Condition tests for ProductFlag and
 
    IncludedProductDiscount. '''
 

	
 
    def __init__(self, condition):
 
        self.condition = condition
 

	
 
    def is_met(self, user):
...
 
@@ -227,13 +227,13 @@ class ProductConditionController(ConditionController):
 
            product__in=self.condition.enabling_products.all(),
 
        ).count()
 
        return products_count > 0
 

	
 

	
 
class TimeOrStockLimitConditionController(ConditionController):
 
    ''' Common condition tests for TimeOrStockLimit EnablingCondition and
 
    ''' Common condition tests for TimeOrStockLimit Flag and
 
    Discount.'''
 

	
 
    def __init__(self, ceiling):
 
        self.ceiling = ceiling
 

	
 
    def user_quantity_remaining(self, user):
...
 
@@ -277,13 +277,13 @@ class TimeOrStockLimitConditionController(ConditionController):
 
        items = items.filter(cart__in=reserved_carts)
 
        count = items.aggregate(Sum("quantity"))["quantity__sum"] or 0
 

	
 
        return self.ceiling.limit - count
 

	
 

	
 
class TimeOrStockLimitEnablingConditionController(
 
class TimeOrStockLimitFlagController(
 
        TimeOrStockLimitConditionController):
 

	
 
    def _items(self):
 
        category_products = rego.Product.objects.filter(
 
            category__in=self.ceiling.categories.all(),
 
        )
...
 
@@ -302,13 +302,13 @@ class TimeOrStockLimitDiscountController(TimeOrStockLimitConditionController):
 
            discount=self.ceiling,
 
        )
 
        return discount_items
 

	
 

	
 
class VoucherConditionController(ConditionController):
 
    ''' Condition test for VoucherEnablingCondition and VoucherDiscount.'''
 
    ''' Condition test for VoucherFlag and VoucherDiscount.'''
 

	
 
    def __init__(self, condition):
 
        self.condition = condition
 

	
 
    def is_met(self, user):
 
        ''' returns True if the user has the given voucher attached. '''
registrasion/controllers/product.py
Show inline comments
...
 
@@ -12,15 +12,15 @@ class ProductController(object):
 
    def __init__(self, product):
 
        self.product = product
 

	
 
    @classmethod
 
    def available_products(cls, user, category=None, products=None):
 
        ''' Returns a list of all of the products that are available per
 
        enabling conditions from the given categories.
 
        flag conditions from the given categories.
 
        TODO: refactor so that all conditions are tested here and
 
        can_add_with_enabling_conditions calls this method. '''
 
        can_add_with_flags calls this method. '''
 
        if category is None and products is None:
 
            raise ValueError("You must provide products or a category")
 

	
 
        if category is not None:
 
            all_products = rego.Product.objects.filter(category=category)
 
            all_products = all_products.select_related("category")
...
 
@@ -42,13 +42,13 @@ class ProductController(object):
 
            product
 
            for product in all_products
 
            if cat_quants[product.category] > 0
 
            if cls(product).user_quantity_remaining(user) > 0
 
        )
 

	
 
        failed_and_messages = ConditionController.test_enabling_conditions(
 
        failed_and_messages = ConditionController.test_flags(
 
            user, products=passed_limits
 
        )
 
        failed_conditions = set(i[0] for i in failed_and_messages)
 

	
 
        out = list(passed_limits - failed_conditions)
 
        out.sort(key=lambda product: product.order)
registrasion/migrations/0021_auto_20160411_0748_squashed_0024_auto_20160411_2230.py
Show inline comments
 
new file 100644
 
# -*- coding: utf-8 -*-
 
# Generated by Django 1.9.2 on 2016-04-11 22:46
 
from __future__ import unicode_literals
 

	
 
from django.db import migrations, models
 

	
 

	
 
class Migration(migrations.Migration):
 

	
 
    dependencies = [
 
        ('registrasion', '0020_auto_20160411_0258'),
 
    ]
 

	
 
    operations = [
 
        migrations.RenameModel(
 
            old_name='CategoryEnablingCondition',
 
            new_name='CategoryFlag',
 
        ),
 
        migrations.RenameModel(
 
            old_name='ProductEnablingCondition',
 
            new_name='ProductFlag',
 
        ),
 
        migrations.RenameModel(
 
            old_name='TimeOrStockLimitEnablingCondition',
 
            new_name='TimeOrStockLimitFlag',
 
        ),
 
        migrations.RenameModel(
 
            old_name='VoucherEnablingCondition',
 
            new_name='VoucherFlag',
 
        ),
 
        migrations.AlterModelOptions(
 
            name='categoryflag',
 
            options={'verbose_name': 'flag (dependency on product from category)', 'verbose_name_plural': 'flags (dependency on product from category)'},
 
        ),
 
        migrations.AlterModelOptions(
 
            name='productflag',
 
            options={'verbose_name': 'flag (dependency on product)', 'verbose_name_plural': 'flags (dependency on product)'},
 
        ),
 
        migrations.AlterModelOptions(
 
            name='timeorstocklimitflag',
 
            options={'verbose_name': 'flag (time/stock limit)', 'verbose_name_plural': 'flags (time/stock limit)'},
 
        ),
 
        migrations.AlterModelOptions(
 
            name='voucherflag',
 
            options={'verbose_name': 'flag (dependency on voucher)', 'verbose_name_plural': 'flags (dependency on voucher)'},
 
        ),
 
        migrations.AlterField(
 
            model_name='enablingconditionbase',
 
            name='categories',
 
            field=models.ManyToManyField(blank=True, help_text="Categories whose products are affected by this flag's condition.", to=b'registrasion.Category'),
 
        ),
 
        migrations.RenameField(
 
            model_name='enablingconditionbase',
 
            old_name='mandatory',
 
            new_name='condition',
 
        ),
 
        migrations.AlterField(
 
            model_name='enablingconditionbase',
 
            name='condition',
 
            field=models.IntegerField(choices=[(1, 'Disable if false'), (2, 'Enable if true')], default=2, help_text="If there is at least one 'disable if false' flag defined on a product or category, all such flag  conditions must be met. If there is at least one 'enable if true' flag, at least one such condition must be met. If both types of conditions exist on a product, both of these rules apply."),
 
        ),
 
        migrations.AlterField(
 
            model_name='enablingconditionbase',
 
            name='products',
 
            field=models.ManyToManyField(blank=True, help_text="Products affected by this flag's condition.", to=b'registrasion.Product'),
 
        ),
 
        migrations.AlterField(
 
            model_name='enablingconditionbase',
 
            name='categories',
 
            field=models.ManyToManyField(blank=True, help_text="Categories whose products are affected by this flag's condition.", related_name='flagbase_set', to=b'registrasion.Category'),
 
        ),
 
        migrations.AlterField(
 
            model_name='enablingconditionbase',
 
            name='products',
 
            field=models.ManyToManyField(blank=True, help_text="Products affected by this flag's condition.", related_name='flagbase_set', to=b'registrasion.Product'),
 
        ),
 
    ]
registrasion/models.py
Show inline comments
...
 
@@ -376,55 +376,95 @@ class RoleDiscount(object):
 
    role. This is for e.g. volunteers who can get a discount ticket. '''
 
    # TODO: implement RoleDiscount
 
    pass
 

	
 

	
 
@python_2_unicode_compatible
 
class EnablingConditionBase(models.Model):
 
class FlagBase(models.Model):
 
    ''' This defines a condition which allows products or categories to
 
    be made visible. If there is at least one mandatory enabling condition
 
    defined on a Product or Category, it will only be enabled if *all*
 
    mandatory conditions are met, otherwise, if there is at least one enabling
 
    condition defined on a Product or Category, it will only be enabled if at
 
    least one condition is met. '''
 
    be made visible, or be prevented from being visible.
 

	
 
    objects = InheritanceManager()
 
    The various subclasses of this can define the conditions that enable
 
    or disable products, by the following rules:
 

	
 
    If there is at least one 'disable if false' flag defined on a product or
 
    category, all such flag conditions must be met. If there is at least one
 
    'enable if true' flag, at least one such condition must be met.
 

	
 
    If both types of conditions exist on a product, both of these rules apply.
 
    '''
 

	
 
    class Meta:
 
        # TODO: make concrete once https://code.djangoproject.com/ticket/26488
 
        # is solved.
 
        abstract = True
 

	
 
    DISABLE_IF_FALSE = 1
 
    ENABLE_IF_TRUE = 2
 

	
 
    def __str__(self):
 
        return self.description
 

	
 
    def effects(self):
 
        ''' Returns all of the items enabled by this condition. '''
 
        ''' Returns all of the items affected by this condition. '''
 
        return itertools.chain(self.products.all(), self.categories.all())
 

	
 
    @property
 
    def is_disable_if_false(self):
 
        return self.condition == FlagBase.DISABLE_IF_FALSE
 

	
 
    @property
 
    def is_enable_if_true(self):
 
        return self.condition == FlagBase.ENABLE_IF_TRUE
 

	
 
    description = models.CharField(max_length=255)
 
    mandatory = models.BooleanField(
 
        default=False,
 
        help_text=_("If there is at least one mandatory condition defined on "
 
                    "a product or category, all such conditions must be met. "
 
                    "Otherwise, at least one non-mandatory condition must be "
 
                    "met."),
 
    condition = models.IntegerField(
 
        default=ENABLE_IF_TRUE,
 
        choices=(
 
            (DISABLE_IF_FALSE, _("Disable if false")),
 
            (ENABLE_IF_TRUE, _("Enable if true")),
 
        ),
 
        help_text=_("If there is at least one 'disable if false' flag "
 
                    "defined on a product or category, all such flag "
 
                    " conditions must be met. If there is at least one "
 
                    "'enable if true' flag, at least one such condition must "
 
                    "be met. If both types of conditions exist on a product, "
 
                    "both of these rules apply."
 
        ),
 
    )
 
    products = models.ManyToManyField(
 
        Product,
 
        blank=True,
 
        help_text=_("Products that are enabled if this condition is met."),
 
        help_text=_("Products affected by this flag's condition."),
 
        related_name="flagbase_set",
 
    )
 
    categories = models.ManyToManyField(
 
        Category,
 
        blank=True,
 
        help_text=_("Categories whose products are enabled if this condition "
 
                    "is met."),
 
        help_text=_("Categories whose products are affected by this flag's "
 
                    "condition."
 
        ),
 
        related_name="flagbase_set",
 
    )
 

	
 

	
 
class TimeOrStockLimitEnablingCondition(EnablingConditionBase):
 
class EnablingConditionBase(FlagBase):
 
    ''' Reifies the abstract FlagBase. This is necessary because django
 
    prevents renaming base classes in migrations. '''
 
    # TODO: remove this, and make subclasses subclass FlagBase once
 
    # https://code.djangoproject.com/ticket/26488 is solved.
 

	
 
    objects = InheritanceManager()
 

	
 

	
 
class TimeOrStockLimitFlag(EnablingConditionBase):
 
    ''' Registration product ceilings '''
 

	
 
    class Meta:
 
        verbose_name = _("ceiling")
 
        verbose_name = _("flag (time/stock limit)")
 
        verbose_name_plural = _("flags (time/stock limit)")
 

	
 
    start_time = models.DateTimeField(
 
        null=True,
 
        blank=True,
 
        help_text=_("Products included in this condition will only be "
 
                    "available after this time."),
...
 
@@ -441,56 +481,68 @@ class TimeOrStockLimitEnablingCondition(EnablingConditionBase):
 
        help_text=_("The number of items under this grouping that can be "
 
                    "purchased."),
 
    )
 

	
 

	
 
@python_2_unicode_compatible
 
class ProductEnablingCondition(EnablingConditionBase):
 
class ProductFlag(EnablingConditionBase):
 
    ''' The condition is met because a specific product is purchased. '''
 

	
 
    class Meta:
 
        verbose_name = _("flag (dependency on product)")
 
        verbose_name_plural = _("flags (dependency on product)")
 

	
 
    def __str__(self):
 
        return "Enabled by products: " + str(self.enabling_products.all())
 

	
 
    enabling_products = models.ManyToManyField(
 
        Product,
 
        help_text=_("If one of these products are purchased, this condition "
 
                    "is met."),
 
    )
 

	
 

	
 
@python_2_unicode_compatible
 
class CategoryEnablingCondition(EnablingConditionBase):
 
class CategoryFlag(EnablingConditionBase):
 
    ''' The condition is met because a product in a particular product is
 
    purchased. '''
 

	
 
    class Meta:
 
        verbose_name = _("flag (dependency on product from category)")
 
        verbose_name_plural = _("flags (dependency on product from category)")
 

	
 
    def __str__(self):
 
        return "Enabled by product in category: " + str(self.enabling_category)
 

	
 
    enabling_category = models.ForeignKey(
 
        Category,
 
        help_text=_("If a product from this category is purchased, this "
 
                    "condition is met."),
 
    )
 

	
 

	
 
@python_2_unicode_compatible
 
class VoucherEnablingCondition(EnablingConditionBase):
 
class VoucherFlag(EnablingConditionBase):
 
    ''' The condition is met because a Voucher is present. This is for e.g.
 
    enabling sponsor tickets. '''
 

	
 
    class Meta:
 
        verbose_name = _("flag (dependency on voucher)")
 
        verbose_name_plural = _("flags (dependency on voucher)")
 

	
 
    def __str__(self):
 
        return "Enabled by voucher: %s" % self.voucher
 

	
 
    voucher = models.OneToOneField(Voucher)
 

	
 

	
 
# @python_2_unicode_compatible
 
class RoleEnablingCondition(object):
 
class RoleFlag(object):
 
    ''' The condition is met because the active user has a particular Role.
 
    This is for e.g. enabling Team tickets. '''
 
    # TODO: implement RoleEnablingCondition
 
    # TODO: implement RoleFlag
 
    pass
 

	
 

	
 
# Commerce Models
 

	
 
@python_2_unicode_compatible
registrasion/tests/test_cart.py
Show inline comments
...
 
@@ -92,29 +92,29 @@ class RegistrationCartTestCase(SetTimeMixin, TestCase):
 
        current_cart = TestingCartController.for_user(cls.USER_2)
 

	
 
        current_cart.next_cart()
 

	
 
    @classmethod
 
    def make_ceiling(cls, name, limit=None, start_time=None, end_time=None):
 
        limit_ceiling = rego.TimeOrStockLimitEnablingCondition.objects.create(
 
        limit_ceiling = rego.TimeOrStockLimitFlag.objects.create(
 
            description=name,
 
            mandatory=True,
 
            condition=rego.FlagBase.DISABLE_IF_FALSE,
 
            limit=limit,
 
            start_time=start_time,
 
            end_time=end_time
 
        )
 
        limit_ceiling.save()
 
        limit_ceiling.products.add(cls.PROD_1, cls.PROD_2)
 
        limit_ceiling.save()
 

	
 
    @classmethod
 
    def make_category_ceiling(
 
            cls, name, limit=None, start_time=None, end_time=None):
 
        limit_ceiling = rego.TimeOrStockLimitEnablingCondition.objects.create(
 
        limit_ceiling = rego.TimeOrStockLimitFlag.objects.create(
 
            description=name,
 
            mandatory=True,
 
            condition=rego.FlagBase.DISABLE_IF_FALSE,
 
            limit=limit,
 
            start_time=start_time,
 
            end_time=end_time
 
        )
 
        limit_ceiling.save()
 
        limit_ceiling.categories.add(cls.CAT_1)
registrasion/tests/test_flag.py
Show inline comments
 
file renamed from registrasion/tests/test_enabling_condition.py to registrasion/tests/test_flag.py
...
 
@@ -9,156 +9,170 @@ from registrasion.controllers.product import ProductController
 

	
 
from test_cart import RegistrationCartTestCase
 

	
 
UTC = pytz.timezone('UTC')
 

	
 

	
 
class EnablingConditionTestCases(RegistrationCartTestCase):
 
class FlagTestCases(RegistrationCartTestCase):
 

	
 
    @classmethod
 
    def add_product_enabling_condition(cls, mandatory=False):
 
        ''' Adds a product enabling condition: adding PROD_1 to a cart is
 
    def add_product_flag(cls, condition=rego.FlagBase.ENABLE_IF_TRUE):
 
        ''' Adds a product flag condition: adding PROD_1 to a cart is
 
        predicated on adding PROD_2 beforehand. '''
 
        enabling_condition = rego.ProductEnablingCondition.objects.create(
 
        flag = rego.ProductFlag.objects.create(
 
            description="Product condition",
 
            mandatory=mandatory,
 
            condition=condition,
 
        )
 
        enabling_condition.save()
 
        enabling_condition.products.add(cls.PROD_1)
 
        enabling_condition.enabling_products.add(cls.PROD_2)
 
        enabling_condition.save()
 
        flag.save()
 
        flag.products.add(cls.PROD_1)
 
        flag.enabling_products.add(cls.PROD_2)
 
        flag.save()
 

	
 
    @classmethod
 
    def add_product_enabling_condition_on_category(cls, mandatory=False):
 
        ''' Adds a product enabling condition that operates on a category:
 
    def add_product_flag_on_category(cls, condition=rego.FlagBase.ENABLE_IF_TRUE):
 
        ''' Adds a product flag condition that operates on a category:
 
        adding an item from CAT_1 is predicated on adding PROD_3 beforehand '''
 
        enabling_condition = rego.ProductEnablingCondition.objects.create(
 
        flag = rego.ProductFlag.objects.create(
 
            description="Product condition",
 
            mandatory=mandatory,
 
            condition=condition,
 
        )
 
        enabling_condition.save()
 
        enabling_condition.categories.add(cls.CAT_1)
 
        enabling_condition.enabling_products.add(cls.PROD_3)
 
        enabling_condition.save()
 
        flag.save()
 
        flag.categories.add(cls.CAT_1)
 
        flag.enabling_products.add(cls.PROD_3)
 
        flag.save()
 

	
 
    def add_category_enabling_condition(cls, mandatory=False):
 
        ''' Adds a category enabling condition: adding PROD_1 to a cart is
 
    def add_category_flag(cls, condition=rego.FlagBase.ENABLE_IF_TRUE):
 
        ''' Adds a category flag condition: adding PROD_1 to a cart is
 
        predicated on adding an item from CAT_2 beforehand.'''
 
        enabling_condition = rego.CategoryEnablingCondition.objects.create(
 
        flag = rego.CategoryFlag.objects.create(
 
            description="Category condition",
 
            mandatory=mandatory,
 
            condition=condition,
 
            enabling_category=cls.CAT_2,
 
        )
 
        enabling_condition.save()
 
        enabling_condition.products.add(cls.PROD_1)
 
        enabling_condition.save()
 
        flag.save()
 
        flag.products.add(cls.PROD_1)
 
        flag.save()
 

	
 
    def test_product_enabling_condition_enables_product(self):
 
        self.add_product_enabling_condition()
 
    def test_product_flag_enables_product(self):
 
        self.add_product_flag()
 

	
 
        # Cannot buy PROD_1 without buying PROD_2
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        with self.assertRaises(ValidationError):
 
            current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
        current_cart.add_to_cart(self.PROD_2, 1)
 
        current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_product_enabled_by_product_in_previous_cart(self):
 
        self.add_product_enabling_condition()
 
        self.add_product_flag()
 

	
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        current_cart.add_to_cart(self.PROD_2, 1)
 

	
 
        current_cart.next_cart()
 

	
 
        # Create new cart and try to add PROD_1
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_product_enabling_condition_enables_category(self):
 
        self.add_product_enabling_condition_on_category()
 
    def test_product_flag_enables_category(self):
 
        self.add_product_flag_on_category()
 

	
 
        # Cannot buy PROD_1 without buying item from CAT_2
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        with self.assertRaises(ValidationError):
 
            current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
        current_cart.add_to_cart(self.PROD_3, 1)
 
        current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_category_enabling_condition_enables_product(self):
 
        self.add_category_enabling_condition()
 
    def test_category_flag_enables_product(self):
 
        self.add_category_flag()
 

	
 
        # Cannot buy PROD_1 without buying PROD_2
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        with self.assertRaises(ValidationError):
 
            current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
        # PROD_3 is in CAT_2
 
        current_cart.add_to_cart(self.PROD_3, 1)
 
        current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_product_enabled_by_category_in_previous_cart(self):
 
        self.add_category_enabling_condition()
 
        self.add_category_flag()
 

	
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        current_cart.add_to_cart(self.PROD_3, 1)
 

	
 
        current_cart.next_cart()
 

	
 
        # Create new cart and try to add PROD_1
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        current_cart.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_multiple_non_mandatory_conditions(self):
 
        self.add_product_enabling_condition()
 
        self.add_category_enabling_condition()
 
    def test_multiple_eit_conditions(self):
 
        self.add_product_flag()
 
        self.add_category_flag()
 

	
 
        # User 1 is testing the product enabling condition
 
        # User 1 is testing the product flag condition
 
        cart_1 = TestingCartController.for_user(self.USER_1)
 
        # Cannot add PROD_1 until a condition is met
 
        with self.assertRaises(ValidationError):
 
            cart_1.add_to_cart(self.PROD_1, 1)
 
        cart_1.add_to_cart(self.PROD_2, 1)
 
        cart_1.add_to_cart(self.PROD_1, 1)
 

	
 
        # User 2 is testing the category enabling condition
 
        # User 2 is testing the category flag condition
 
        cart_2 = TestingCartController.for_user(self.USER_2)
 
        # Cannot add PROD_1 until a condition is met
 
        with self.assertRaises(ValidationError):
 
            cart_2.add_to_cart(self.PROD_1, 1)
 
        cart_2.add_to_cart(self.PROD_3, 1)
 
        cart_2.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_multiple_mandatory_conditions(self):
 
        self.add_product_enabling_condition(mandatory=True)
 
        self.add_category_enabling_condition(mandatory=True)
 
    def test_multiple_dif_conditions(self):
 
        self.add_product_flag(condition=rego.FlagBase.DISABLE_IF_FALSE)
 
        self.add_category_flag(condition=rego.FlagBase.DISABLE_IF_FALSE)
 

	
 
        cart_1 = TestingCartController.for_user(self.USER_1)
 
        # Cannot add PROD_1 until both conditions are met
 
        with self.assertRaises(ValidationError):
 
            cart_1.add_to_cart(self.PROD_1, 1)
 
        cart_1.add_to_cart(self.PROD_2, 1)  # Meets the product condition
 
        with self.assertRaises(ValidationError):
 
            cart_1.add_to_cart(self.PROD_1, 1)
 
        cart_1.add_to_cart(self.PROD_3, 1)  # Meets the category condition
 
        cart_1.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_mandatory_conditions_are_mandatory(self):
 
        self.add_product_enabling_condition(mandatory=False)
 
        self.add_category_enabling_condition(mandatory=True)
 
    def test_eit_and_dif_conditions_work_together(self):
 
        self.add_product_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 
        self.add_category_flag(condition=rego.FlagBase.DISABLE_IF_FALSE)
 

	
 
        cart_1 = TestingCartController.for_user(self.USER_1)
 
        # Cannot add PROD_1 until both conditions are met
 
        with self.assertRaises(ValidationError):
 
            cart_1.add_to_cart(self.PROD_1, 1)
 
        cart_1.add_to_cart(self.PROD_2, 1)  # Meets the product condition
 

	
 
        cart_1.add_to_cart(self.PROD_2, 1)  # Meets the EIT condition
 

	
 
        # Need to meet both conditions before you can add
 
        with self.assertRaises(ValidationError):
 
            cart_1.add_to_cart(self.PROD_1, 1)
 
        cart_1.add_to_cart(self.PROD_3, 1)  # Meets the category condition
 

	
 
        cart_1.set_quantity(self.PROD_2, 0)  # Un-meets the EIT condition
 

	
 
        cart_1.add_to_cart(self.PROD_3, 1)  # Meets the DIF condition
 

	
 
        # Need to meet both conditions before you can add
 
        with self.assertRaises(ValidationError):
 
            cart_1.add_to_cart(self.PROD_1, 1)
 

	
 
        cart_1.add_to_cart(self.PROD_2, 1)  # Meets the EIT condition
 

	
 
        # Now that both conditions are met, we can add the product
 
        cart_1.add_to_cart(self.PROD_1, 1)
 

	
 
    def test_available_products_works_with_no_conditions_set(self):
 
        prods = ProductController.available_products(
 
            self.USER_1,
 
            category=self.CAT_1,
...
 
@@ -183,24 +197,24 @@ class EnablingConditionTestCases(RegistrationCartTestCase):
 
        self.assertTrue(self.PROD_1 in prods)
 
        self.assertTrue(self.PROD_2 in prods)
 
        self.assertTrue(self.PROD_3 in prods)
 
        self.assertTrue(self.PROD_4 in prods)
 

	
 
    def test_available_products_on_category_works_when_condition_not_met(self):
 
        self.add_product_enabling_condition(mandatory=False)
 
        self.add_product_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        prods = ProductController.available_products(
 
            self.USER_1,
 
            category=self.CAT_1,
 
        )
 

	
 
        self.assertTrue(self.PROD_1 not in prods)
 
        self.assertTrue(self.PROD_2 in prods)
 

	
 
    def test_available_products_on_category_works_when_condition_is_met(self):
 
        self.add_product_enabling_condition(mandatory=False)
 
        self.add_product_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        cart_1 = TestingCartController.for_user(self.USER_1)
 
        cart_1.add_to_cart(self.PROD_2, 1)
 

	
 
        prods = ProductController.available_products(
 
            self.USER_1,
...
 
@@ -208,38 +222,38 @@ class EnablingConditionTestCases(RegistrationCartTestCase):
 
        )
 

	
 
        self.assertTrue(self.PROD_1 in prods)
 
        self.assertTrue(self.PROD_2 in prods)
 

	
 
    def test_available_products_on_products_works_when_condition_not_met(self):
 
        self.add_product_enabling_condition(mandatory=False)
 
        self.add_product_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        prods = ProductController.available_products(
 
            self.USER_1,
 
            products=[self.PROD_1, self.PROD_2],
 
        )
 

	
 
        self.assertTrue(self.PROD_1 not in prods)
 
        self.assertTrue(self.PROD_2 in prods)
 

	
 
    def test_available_products_on_products_works_when_condition_is_met(self):
 
        self.add_product_enabling_condition(mandatory=False)
 
        self.add_product_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        cart_1 = TestingCartController.for_user(self.USER_1)
 
        cart_1.add_to_cart(self.PROD_2, 1)
 

	
 
        prods = ProductController.available_products(
 
            self.USER_1,
 
            products=[self.PROD_1, self.PROD_2],
 
        )
 

	
 
        self.assertTrue(self.PROD_1 in prods)
 
        self.assertTrue(self.PROD_2 in prods)
 

	
 
    def test_category_enabling_condition_fails_if_cart_refunded(self):
 
        self.add_category_enabling_condition(mandatory=False)
 
    def test_category_flag_fails_if_cart_refunded(self):
 
        self.add_category_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        cart = TestingCartController.for_user(self.USER_1)
 
        cart.add_to_cart(self.PROD_3, 1)
 

	
 
        cart.next_cart()
 

	
...
 
@@ -250,14 +264,14 @@ class EnablingConditionTestCases(RegistrationCartTestCase):
 
        cart.cart.released = True
 
        cart.next_cart()
 

	
 
        with self.assertRaises(ValidationError):
 
            cart_2.set_quantity(self.PROD_1, 1)
 

	
 
    def test_product_enabling_condition_fails_if_cart_refunded(self):
 
        self.add_product_enabling_condition(mandatory=False)
 
    def test_product_flag_fails_if_cart_refunded(self):
 
        self.add_product_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        cart = TestingCartController.for_user(self.USER_1)
 
        cart.add_to_cart(self.PROD_2, 1)
 

	
 
        cart.next_cart()
 

	
...
 
@@ -269,13 +283,13 @@ class EnablingConditionTestCases(RegistrationCartTestCase):
 
        cart.next_cart()
 

	
 
        with self.assertRaises(ValidationError):
 
            cart_2.set_quantity(self.PROD_1, 1)
 

	
 
    def test_available_categories(self):
 
        self.add_product_enabling_condition_on_category(mandatory=False)
 
        self.add_product_flag_on_category(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        cart_1 = TestingCartController.for_user(self.USER_1)
 

	
 
        cats = CategoryController.available_categories(
 
            self.USER_1,
 
        )
...
 
@@ -289,14 +303,14 @@ class EnablingConditionTestCases(RegistrationCartTestCase):
 
            self.USER_1,
 
        )
 

	
 
        self.assertTrue(self.CAT_1 in cats)
 
        self.assertTrue(self.CAT_2 in cats)
 

	
 
    def test_validate_cart_when_enabling_conditions_become_unmet(self):
 
        self.add_product_enabling_condition(mandatory=False)
 
    def test_validate_cart_when_flags_become_unmet(self):
 
        self.add_product_flag(condition=rego.FlagBase.ENABLE_IF_TRUE)
 

	
 
        cart = TestingCartController.for_user(self.USER_1)
 
        cart.add_to_cart(self.PROD_2, 1)
 
        cart.add_to_cart(self.PROD_1, 1)
 

	
 
        # Should pass
...
 
@@ -306,13 +320,13 @@ class EnablingConditionTestCases(RegistrationCartTestCase):
 

	
 
        # Should fail
 
        with self.assertRaises(ValidationError):
 
            cart.validate_cart()
 

	
 
    def test_fix_simple_errors_resolves_unavailable_products(self):
 
        self.test_validate_cart_when_enabling_conditions_become_unmet()
 
        self.test_validate_cart_when_flags_become_unmet()
 
        cart = TestingCartController.for_user(self.USER_1)
 

	
 
        # Should just remove all of the unavailable products
 
        cart.fix_simple_errors()
 
        # Should now succeed
 
        cart.validate_cart()
registrasion/tests/test_voucher.py
Show inline comments
...
 
@@ -55,20 +55,20 @@ class VoucherTestCases(RegistrationCartTestCase):
 
        # This should work now.
 
        cart_1.validate_cart()
 

	
 
    def test_voucher_enables_item(self):
 
        voucher = self.new_voucher()
 

	
 
        enabling_condition = rego.VoucherEnablingCondition.objects.create(
 
        flag = rego.VoucherFlag.objects.create(
 
            description="Voucher condition",
 
            voucher=voucher,
 
            mandatory=False,
 
            condition=rego.FlagBase.ENABLE_IF_TRUE,
 
        )
 
        enabling_condition.save()
 
        enabling_condition.products.add(self.PROD_1)
 
        enabling_condition.save()
 
        flag.save()
 
        flag.products.add(self.PROD_1)
 
        flag.save()
 

	
 
        # Adding the product without a voucher will not work
 
        current_cart = TestingCartController.for_user(self.USER_1)
 
        with self.assertRaises(ValidationError):
 
            current_cart.add_to_cart(self.PROD_1, 1)
 

	
0 comments (0 inline, 0 general)