INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns tab - delimited newline terminated string of VcfRecord. | def text(self):
"Returns tab-delimited, newline terminated string of VcfRecord."
stringifier = [self.chrom, self.pos, self.vcf_id, self.ref, self.alt,
self.qual, self.filter, self.info,
self._format_field()]
for sample in self.sample_tag_values:
stringifier.append(self._sample_field(sample))
return "\t".join(stringifier) + "\n" |
Appends a new format tag - value for all samples. | def add_sample_tag_value(self, tag_name, new_sample_values):
"""Appends a new format tag-value for all samples.
Args:
tag_name: string tag name; must not already exist
new_sample
Raises:
KeyError: if tag_name to be added already exists
"""
if tag_name in self.format_tags:
msg = "New format value [{}] already exists.".format(tag_name)
raise KeyError(msg)
if not self._samples_match(new_sample_values):
raise KeyError("Sample name values must match "
"existing sample names")
for sample in self.sample_tag_values.keys():
value = str(new_sample_values[sample])
self.sample_tag_values[sample][tag_name] = value |
Replaces null or blank filter or adds filter to existing list. | def add_or_replace_filter(self, new_filter):
"""Replaces null or blank filter or adds filter to existing list."""
if self.filter.lower() in self._FILTERS_TO_REPLACE:
self.filter = new_filter
elif new_filter not in self.filter.split(";"):
self.filter = ";".join([self.filter,
new_filter]) |
Returns the categories available to the user. Specify products if you want to restrict to just the categories that hold the specified products otherwise it ll do all. | def available_categories(cls, user, products=AllProducts):
''' Returns the categories available to the user. Specify `products` if
you want to restrict to just the categories that hold the specified
products, otherwise it'll do all. '''
# STOPGAP -- this needs to be elsewhere tbqh
from .product import ProductController
if products is AllProducts:
products = inventory.Product.objects.all().select_related(
"category",
)
available = ProductController.available_products(
user,
products=products,
)
return sorted(set(i.category for i in available), key=attrgetter("order")) |
Produces an appropriate _ProductsForm subclass for the given render type. | def ProductsForm(category, products):
''' Produces an appropriate _ProductsForm subclass for the given render
type. '''
# Each Category.RENDER_TYPE value has a subclass here.
cat = inventory.Category
RENDER_TYPES = {
cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
cat.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
cat.RENDER_TYPE_ITEM_QUANTITY: _ItemQuantityProductsForm,
cat.RENDER_TYPE_CHECKBOX: _CheckboxProductsForm,
}
# Produce a subclass of _ProductsForm which we can alter the base_fields on
class ProductsForm(RENDER_TYPES[category.render_type]):
pass
products = list(products)
products.sort(key=lambda prod: prod.order)
ProductsForm.set_fields(category, products)
if category.render_type == inventory.Category.RENDER_TYPE_ITEM_QUANTITY:
ProductsForm = forms.formset_factory(
ProductsForm,
formset=_ItemQuantityProductsFormSet,
)
return ProductsForm |
Creates a StaffProductsForm that restricts the available products to those that are available to a user. | def staff_products_form_factory(user):
''' Creates a StaffProductsForm that restricts the available products to
those that are available to a user. '''
products = inventory.Product.objects.all()
products = ProductController.available_products(user, products=products)
product_ids = [product.id for product in products]
product_set = inventory.Product.objects.filter(id__in=product_ids)
class StaffProductsForm(forms.Form):
''' Form for allowing staff to add an item to a user's cart. '''
product = forms.ModelChoiceField(
widget=forms.Select,
queryset=product_set,
)
quantity = forms.IntegerField(
min_value=0,
)
return StaffProductsForm |
Adds an error to the given product s field | def add_product_error(self, product, error):
''' Adds an error to the given product's field '''
''' if product in field_names:
field = field_names[product]
elif isinstance(product, inventory.Product):
return
else:
field = None '''
self.add_error(self.field_name(product), error) |
Prepares initial data for an instance of this form. product_quantities is a sequence of ( product quantity ) tuples | def initial_data(cls, product_quantities):
''' Prepares initial data for an instance of this form.
product_quantities is a sequence of (product,quantity) tuples '''
f = [
{
_ItemQuantityProductsForm.CHOICE_FIELD: product.id,
_ItemQuantityProductsForm.QUANTITY_FIELD: quantity,
}
for product, quantity in product_quantities
if quantity > 0
]
return f |
Yields a sequence of ( product quantity ) tuples from the cleaned form data. | def product_quantities(self):
''' Yields a sequence of (product, quantity) tuples from the
cleaned form data. '''
products = set()
# Track everything so that we can yield some zeroes
all_products = set()
for form in self:
if form.empty_permitted and not form.cleaned_data:
# This is the magical empty form at the end of the list.
continue
for product, quantity in form.product_quantities():
all_products.add(product)
if quantity == 0:
continue
if product in products:
form.add_error(
_ItemQuantityProductsForm.CHOICE_FIELD,
"You may only choose each product type once.",
)
form.add_error(
_ItemQuantityProductsForm.QUANTITY_FIELD,
"You may only choose each product type once.",
)
products.add(product)
yield product, quantity
for product in (all_products - products):
yield product, 0 |
Decorator that stores the result of the stored function in the user s results cache until the batch completes. Keyword arguments are not yet supported. | def memoise(cls, func):
''' Decorator that stores the result of the stored function in the
user's results cache until the batch completes. Keyword arguments are
not yet supported.
Arguments:
func (callable(*a)): The function whose results we want
to store. The positional arguments, ``a``, are used as cache
keys.
Returns:
callable(*a): The memosing version of ``func``.
'''
@functools.wraps(func)
def f(*a):
for arg in a:
if isinstance(arg, User):
user = arg
break
else:
raise ValueError("One position argument must be a User")
func_key = (func, tuple(a))
cache = cls.get_cache(user)
if func_key not in cache:
cache[func_key] = func(*a)
return cache[func_key]
return f |
Creates a form for specifying fields from a model to display. | def model_fields_form_factory(model):
''' Creates a form for specifying fields from a model to display. '''
fields = model._meta.get_fields()
choices = []
for field in fields:
if hasattr(field, "verbose_name"):
choices.append((field.name, field.verbose_name))
class ModelFieldsForm(forms.Form):
fields = forms.MultipleChoiceField(
choices=choices,
required=False,
)
return ModelFieldsForm |
Aggregates the items that this user has purchased. | def _items(self, cart_status, category=None):
''' Aggregates the items that this user has purchased.
Arguments:
cart_status (int or Iterable(int)): etc
category (Optional[models.inventory.Category]): the category
of items to restrict to.
Returns:
[ProductAndQuantity, ...]: A list of product-quantity pairs,
aggregating like products from across multiple invoices.
'''
if not isinstance(cart_status, Iterable):
cart_status = [cart_status]
status_query = (
Q(productitem__cart__status=status) for status in cart_status
)
in_cart = Q(productitem__cart__user=self.user)
in_cart = in_cart & reduce(operator.__or__, status_query)
quantities_in_cart = When(
in_cart,
then="productitem__quantity",
)
quantities_or_zero = Case(
quantities_in_cart,
default=Value(0),
)
products = inventory.Product.objects
if category:
products = products.filter(category=category)
products = products.select_related("category")
products = products.annotate(quantity=Sum(quantities_or_zero))
products = products.filter(quantity__gt=0)
out = []
for prod in products:
out.append(ProductAndQuantity(prod, prod.quantity))
return out |
Returns the items that this user has purchased or has pending. | def items_pending_or_purchased(self):
''' Returns the items that this user has purchased or has pending. '''
status = [commerce.Cart.STATUS_PAID, commerce.Cart.STATUS_ACTIVE]
return self._items(status) |
Aggregates the items that this user has purchased. | def items_purchased(self, category=None):
''' Aggregates the items that this user has purchased.
Arguments:
category (Optional[models.inventory.Category]): the category
of items to restrict to.
Returns:
[ProductAndQuantity, ...]: A list of product-quantity pairs,
aggregating like products from across multiple invoices.
'''
return self._items(commerce.Cart.STATUS_PAID, category=category) |
Sends an e - mail to the given address. | def send_email(self, to, kind, **kwargs):
''' Sends an e-mail to the given address.
to: The address
kind: the ID for an e-mail kind; it should point to a subdirectory of
self.template_prefix containing subject.txt and message.html, which
are django templates for the subject and HTML message respectively.
context: a context for rendering the e-mail.
'''
return __send_email__(self.template_prefix, to, kind, **kwargs) |
Start processing an OSM changeset stream and yield one ( action primitive ) tuple at a time to the caller. | def iter_changeset_stream(start_sqn=None, base_url='https://planet.openstreetmap.org/replication/changesets', expected_interval=60, parse_timestamps=True, state_dir=None):
"""Start processing an OSM changeset stream and yield one (action, primitive) tuple
at a time to the caller."""
# This is a lot like the other osm_stream except there's no
# state file for each of the diffs, so just push ahead until
# we run into a 404.
# If the user specifies a state_dir, read the state from the statefile there
if state_dir:
if not os.path.exists(state_dir):
raise Exception('Specified state_dir "%s" doesn\'t exist.' % state_dir)
if os.path.exists('%s/state.yaml' % state_dir):
with open('%s/state.yaml' % state_dir) as f:
state = readState(f, ': ')
start_sqn = state['sequence']
# If no start_sqn, assume to start from the most recent changeset file
if not start_sqn:
u = urllib2.urlopen('%s/state.yaml' % base_url)
state = readState(u, ': ')
sequenceNumber = int(state['sequence'])
else:
sequenceNumber = int(start_sqn)
interval_fudge = 0.0
while True:
sqnStr = str(sequenceNumber).zfill(9)
url = '%s/%s/%s/%s.osm.gz' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])
delay = 1.0
while True:
try:
content = urllib2.urlopen(url)
content = StringIO.StringIO(content.read())
gzipper = gzip.GzipFile(fileobj=content)
interval_fudge -= (interval_fudge / 2.0)
break
except urllib2.HTTPError as e:
if e.code == 404:
time.sleep(delay)
delay = min(delay * 2, 13)
interval_fudge += delay
obj = None
for event, elem in etree.iterparse(gzipper, events=('start', 'end')):
if event == 'start':
if elem.tag == 'changeset':
obj = model.Changeset(
int(elem.attrib['id']),
isoToDatetime(elem.attrib.get('created_at')) if parse_timestamps else elem.attrib.get('created_at'),
isoToDatetime(elem.attrib.get('closed_at')) if parse_timestamps else elem.attrib.get('closed_at'),
maybeBool(elem.attrib['open']),
maybeFloat(elem.get('min_lat')),
maybeFloat(elem.get('max_lat')),
maybeFloat(elem.get('min_lon')),
maybeFloat(elem.get('max_lon')),
elem.attrib.get('user'),
maybeInt(elem.attrib.get('uid')),
[]
)
elif elem.tag == 'tag':
obj.tags.append(
model.Tag(
elem.attrib['k'],
elem.attrib['v']
)
)
elif event == 'end':
if elem.tag == 'changeset':
yield obj
obj = None
yield model.Finished(sequenceNumber, None)
sequenceNumber += 1
if state_dir:
with open('%s/state.yaml' % state_dir, 'w') as f:
f.write('sequence: %d' % sequenceNumber) |
Start processing an OSM diff stream and yield one changeset at a time to the caller. | def iter_osm_stream(start_sqn=None, base_url='https://planet.openstreetmap.org/replication/minute', expected_interval=60, parse_timestamps=True, state_dir=None):
"""Start processing an OSM diff stream and yield one changeset at a time to
the caller."""
# If the user specifies a state_dir, read the state from the statefile there
if state_dir:
if not os.path.exists(state_dir):
raise Exception('Specified state_dir "%s" doesn\'t exist.' % state_dir)
if os.path.exists('%s/state.txt' % state_dir):
with open('%s/state.txt' % state_dir) as f:
state = readState(f)
start_sqn = state['sequenceNumber']
# If no start_sqn, assume to start from the most recent diff
if not start_sqn:
u = urllib2.urlopen('%s/state.txt' % base_url)
state = readState(u)
else:
sqnStr = str(start_sqn).zfill(9)
u = urllib2.urlopen('%s/%s/%s/%s.state.txt' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9]))
state = readState(u)
interval_fudge = 0.0
while True:
sqnStr = state['sequenceNumber'].zfill(9)
url = '%s/%s/%s/%s.osc.gz' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])
content = urllib2.urlopen(url)
content = StringIO.StringIO(content.read())
gzipper = gzip.GzipFile(fileobj=content)
for a in iter_osm_change_file(gzipper, parse_timestamps):
yield a
# After parsing the OSC, check to see how much time is remaining
stateTs = datetime.datetime.strptime(state['timestamp'], "%Y-%m-%dT%H:%M:%SZ")
yield (None, model.Finished(state['sequenceNumber'], stateTs))
nextTs = stateTs + datetime.timedelta(seconds=expected_interval + interval_fudge)
if datetime.datetime.utcnow() < nextTs:
timeToSleep = (nextTs - datetime.datetime.utcnow()).total_seconds()
else:
timeToSleep = 0.0
time.sleep(timeToSleep)
# Then try to fetch the next state file
sqnStr = str(int(state['sequenceNumber']) + 1).zfill(9)
url = '%s/%s/%s/%s.state.txt' % (base_url, sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])
delay = 1.0
while True:
try:
u = urllib2.urlopen(url)
interval_fudge -= (interval_fudge / 2.0)
break
except urllib2.HTTPError as e:
if e.code == 404:
time.sleep(delay)
delay = min(delay * 2, 13)
interval_fudge += delay
if state_dir:
with open('%s/state.txt' % state_dir, 'w') as f:
f.write(u.read())
with open('%s/state.txt' % state_dir, 'r') as f:
state = readState(f)
else:
state = readState(u) |
Parse a file - like containing OSM XML into memory and return an object with the nodes ways and relations it contains. | def parse_osm_file(f, parse_timestamps=True):
"""Parse a file-like containing OSM XML into memory and return an object with
the nodes, ways, and relations it contains. """
nodes = []
ways = []
relations = []
for p in iter_osm_file(f, parse_timestamps):
if type(p) == model.Node:
nodes.append(p)
elif type(p) == model.Way:
ways.append(p)
elif type(p) == model.Relation:
relations.append(p)
return (nodes, ways, relations) |
Parses the global OSM Notes feed and yields as much Note information as possible. | def iter_osm_notes(feed_limit=25, interval=60, parse_timestamps=True):
""" Parses the global OSM Notes feed and yields as much Note information as possible. """
last_seen_guid = None
while True:
u = urllib2.urlopen('https://www.openstreetmap.org/api/0.6/notes/feed?limit=%d' % feed_limit)
tree = etree.parse(u)
new_notes = []
for note_item in tree.xpath('/rss/channel/item'):
title = note_item.xpath('title')[0].text
if title.startswith('new note ('):
action = 'create'
elif title.startswith('new comment ('):
action = 'comment'
elif title.startswith('closed note ('):
action = 'close'
# Note that (at least for now) the link and guid are the same in the feed.
guid = note_item.xpath('link')[0].text
if last_seen_guid == guid:
break
elif last_seen_guid == None:
# The first time through we want the first item to be the "last seen"
# because the RSS feed is newest-to-oldest
last_seen_guid = guid
else:
note_id = int(guid.split('/')[-1].split('#c')[0])
new_notes.append((action, get_note(note_id, parse_timestamps)))
# We yield the reversed list because we want to yield in change order
# (i.e. "oldest to most current")
for note in reversed(new_notes):
yield note
yield model.Finished(None, None)
time.sleep(interval) |
Returns true if the condition passes the filter | def passes_filter(self, user):
''' Returns true if the condition passes the filter '''
cls = type(self.condition)
qs = cls.objects.filter(pk=self.condition.id)
return self.condition in self.pre_filter(qs, user) |
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. | def user_quantity_remaining(self, user, filtered=False):
''' 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 _BIG_QUANTITY if self.is_met(user, filtered) else 0 |
Returns True if this flag condition is met otherwise returns False. It determines if the condition is met by calling pre_filter with a queryset containing only self. condition. | def is_met(self, user, filtered=False):
''' Returns True if this flag condition is met, otherwise returns
False. It determines if the condition is met by calling pre_filter
with a queryset containing only self.condition. '''
if filtered:
return True # Why query again?
return self.passes_filter(user) |
returns 0 if the date range is violated otherwise it will return the quantity remaining under the stock limit. | def user_quantity_remaining(self, user, filtered=True):
''' returns 0 if the date range is violated, otherwise, it will return
the quantity remaining under the stock limit.
The filter for this condition must add an annotation called "remainder"
in order for this to work.
'''
if filtered:
if hasattr(self.condition, "remainder"):
return self.condition.remainder
# Mark self.condition with a remainder
qs = type(self.condition).objects.filter(pk=self.condition.id)
qs = self.pre_filter(qs, user)
if len(qs) > 0:
return qs[0].remainder
else:
return 0 |
Returns all of the items from queryset where the user has a product from a category invoking that item s condition in one of their carts. | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset where the user has a
product from a category invoking that item's condition in one of their
carts. '''
in_user_carts = Q(
enabling_category__product__productitem__cart__user=user
)
released = commerce.Cart.STATUS_RELEASED
in_released_carts = Q(
enabling_category__product__productitem__cart__status=released
)
queryset = queryset.filter(in_user_carts)
queryset = queryset.exclude(in_released_carts)
return queryset |
Returns all of the items from queryset where the user has a product invoking that item s condition in one of their carts. | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset where the user has a
product invoking that item's condition in one of their carts. '''
in_user_carts = Q(enabling_products__productitem__cart__user=user)
released = commerce.Cart.STATUS_RELEASED
paid = commerce.Cart.STATUS_PAID
active = commerce.Cart.STATUS_ACTIVE
in_released_carts = Q(
enabling_products__productitem__cart__status=released
)
not_in_paid_or_active_carts = ~(
Q(enabling_products__productitem__cart__status=paid) |
Q(enabling_products__productitem__cart__status=active)
)
queryset = queryset.filter(in_user_carts)
queryset = queryset.exclude(
in_released_carts & not_in_paid_or_active_carts
)
return queryset |
Returns all of the items from queryset where the date falls into any specified range but not yet where the stock limit is not yet reached. | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset where the date falls into
any specified range, but not yet where the stock limit is not yet
reached.'''
now = timezone.now()
# Keep items with no start time, or start time not yet met.
queryset = queryset.filter(Q(start_time=None) | Q(start_time__lte=now))
queryset = queryset.filter(Q(end_time=None) | Q(end_time__gte=now))
# Filter out items that have been reserved beyond the limits
quantity_or_zero = self._calculate_quantities(user)
remainder = Case(
When(limit=None, then=Value(_BIG_QUANTITY)),
default=F("limit") - Sum(quantity_or_zero),
)
queryset = queryset.annotate(remainder=remainder)
queryset = queryset.filter(remainder__gt=0)
return queryset |
Returns all of the items from queryset which are enabled by a user being a presenter or copresenter of a non - cancelled proposal. | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset which are enabled by a user
being a presenter or copresenter of a non-cancelled proposal. '''
# Filter out cancelled proposals
queryset = queryset.filter(
proposal_kind__proposalbase__presentation__cancelled=False
)
u = user
# User is a presenter
user_is_presenter = Q(
is_presenter=True,
proposal_kind__proposalbase__presentation__speaker__user=u,
)
# User is a copresenter
user_is_copresenter = Q(
is_copresenter=True,
proposal_kind__proposalbase__presentation__additional_speakers__user=u, # NOQA
)
return queryset.filter(user_is_presenter | user_is_copresenter) |
Returns all of the items from conditions which are enabled by a user being member of a Django Auth Group. | def pre_filter(self, conditions, user):
''' Returns all of the items from conditions which are enabled by a
user being member of a Django Auth Group. '''
return conditions.filter(group__in=user.groups.all()) |
Decorator that makes the wrapped function raise ValidationError if we re doing something that could modify the cart. | def _modifies_cart(func):
''' Decorator that makes the wrapped function raise ValidationError
if we're doing something that could modify the cart.
It also wraps the execution of this function in a database transaction,
and marks the boundaries of a cart operations batch.
'''
@functools.wraps(func)
def inner(self, *a, **k):
self._fail_if_cart_is_not_active()
with transaction.atomic():
with BatchController.batch(self.cart.user):
# Mark the version of self in the batch cache as modified
memoised = self.for_user(self.cart.user)
memoised._modified_by_batch = True
return func(self, *a, **k)
return inner |
Returns the user s current cart or creates a new cart if there isn t one ready yet. | def for_user(cls, user):
''' Returns the user's current cart, or creates a new cart
if there isn't one ready yet. '''
try:
existing = commerce.Cart.objects.get(
user=user,
status=commerce.Cart.STATUS_ACTIVE,
)
except ObjectDoesNotExist:
existing = commerce.Cart.objects.create(
user=user,
time_last_updated=timezone.now(),
reservation_duration=datetime.timedelta(),
)
return cls(existing) |
Updates the cart s time last updated value which is used to determine whether the cart has reserved the items and discounts it holds. | def _autoextend_reservation(self):
''' Updates the cart's time last updated value, which is used to
determine whether the cart has reserved the items and discounts it
holds. '''
time = timezone.now()
# Calculate the residual of the _old_ reservation duration
# if it's greater than what's in the cart now, keep it.
time_elapsed_since_updated = (time - self.cart.time_last_updated)
residual = self.cart.reservation_duration - time_elapsed_since_updated
reservations = [datetime.timedelta(0), residual]
# If we have vouchers, we're entitled to an hour at minimum.
if len(self.cart.vouchers.all()) >= 1:
reservations.append(inventory.Voucher.RESERVATION_DURATION)
# Else, it's the maximum of the included products
items = commerce.ProductItem.objects.filter(cart=self.cart)
agg = items.aggregate(Max("product__reservation_duration"))
product_max = agg["product__reservation_duration__max"]
if product_max is not None:
reservations.append(product_max)
self.cart.time_last_updated = time
self.cart.reservation_duration = max(reservations) |
Performs operations that occur occur at the end of a batch of product changes/ voucher applications etc. | def _end_batch(self):
''' Performs operations that occur occur at the end of a batch of
product changes/voucher applications etc.
You need to call this after you've finished modifying the user's cart.
This is normally done by wrapping a block of code using
``operations_batch``.
'''
self.cart.refresh_from_db()
self._recalculate_discounts()
self._autoextend_reservation()
self.cart.revision += 1
self.cart.save() |
Extends the reservation on this cart by the given timedelta. This can only be done if the current state of the cart is valid ( i. e all items and discounts in the cart are still available. ) | def extend_reservation(self, timedelta):
''' Extends the reservation on this cart by the given timedelta.
This can only be done if the current state of the cart is valid (i.e
all items and discounts in the cart are still available.)
Arguments:
timedelta (timedelta): The amount of time to extend the cart by.
The resulting reservation_duration will be now() + timedelta,
unless the requested extension is *LESS* than the current
reservation deadline.
'''
self.validate_cart()
cart = self.cart
cart.refresh_from_db()
elapsed = (timezone.now() - cart.time_last_updated)
if cart.reservation_duration - elapsed > timedelta:
return
cart.time_last_updated = timezone.now()
cart.reservation_duration = timedelta
cart.save() |
Sets the quantities on each of the products on each of the products specified. Raises an exception ( ValidationError ) if a limit is violated. product_quantities is an iterable of ( product quantity ) pairs. | def set_quantities(self, product_quantities):
''' Sets the quantities on each of the products on each of the
products specified. Raises an exception (ValidationError) if a limit
is violated. `product_quantities` is an iterable of (product, quantity)
pairs. '''
items_in_cart = commerce.ProductItem.objects.filter(cart=self.cart)
items_in_cart = items_in_cart.select_related(
"product",
"product__category",
)
product_quantities = list(product_quantities)
# n.b need to add have the existing items first so that the new
# items override the old ones.
all_product_quantities = dict(itertools.chain(
((i.product, i.quantity) for i in items_in_cart.all()),
product_quantities,
)).items()
# Validate that the limits we're adding are OK
products = set(product for product, q in product_quantities)
try:
self._test_limits(all_product_quantities)
except CartValidationError as ve:
# Only raise errors for products that we're explicitly
# Manipulating here.
for ve_field in ve.error_list:
product, message = ve_field.message
if product in products:
raise ve
new_items = []
products = []
for product, quantity in product_quantities:
products.append(product)
if quantity == 0:
continue
item = commerce.ProductItem(
cart=self.cart,
product=product,
quantity=quantity,
)
new_items.append(item)
to_delete = (
Q(quantity=0) |
Q(product__in=products)
)
items_in_cart.filter(to_delete).delete()
commerce.ProductItem.objects.bulk_create(new_items) |
Applies the voucher with the given code to this cart. | def apply_voucher(self, voucher_code):
''' Applies the voucher with the given code to this cart. '''
# Try and find the voucher
voucher = inventory.Voucher.objects.get(code=voucher_code.upper())
# Re-applying vouchers should be idempotent
if voucher in self.cart.vouchers.all():
return
self._test_voucher(voucher)
# If successful...
self.cart.vouchers.add(voucher) |
Determines whether the status of the current cart is valid ; this is normally called before generating or paying an invoice | def validate_cart(self):
''' Determines whether the status of the current cart is valid;
this is normally called before generating or paying an invoice '''
cart = self.cart
user = self.cart.user
errors = []
try:
self._test_vouchers(self.cart.vouchers.all())
except ValidationError as ve:
errors.append(ve)
items = commerce.ProductItem.objects.filter(cart=cart)
items = items.select_related("product", "product__category")
product_quantities = list((i.product, i.quantity) for i in items)
try:
self._test_limits(product_quantities)
except ValidationError as ve:
self._append_errors(errors, ve)
try:
self._test_required_categories()
except ValidationError as ve:
self._append_errors(errors, ve)
# Validate the discounts
# TODO: refactor in terms of available_discounts
# why aren't we doing that here?!
# def available_discounts(cls, user, categories, products):
products = [i.product for i in items]
discounts_with_quantity = DiscountController.available_discounts(
user,
[],
products,
)
discounts = set(i.discount.id for i in discounts_with_quantity)
discount_items = commerce.DiscountItem.objects.filter(cart=cart)
for discount_item in discount_items:
discount = discount_item.discount
if discount.id not in discounts:
errors.append(
ValidationError("Discounts are no longer available")
)
if errors:
raise ValidationError(errors) |
This attempts to fix the easy errors raised by ValidationError. This includes removing items from the cart that are no longer available recalculating all of the discounts and removing voucher codes that are no longer available. | def fix_simple_errors(self):
''' This attempts to fix the easy errors raised by ValidationError.
This includes removing items from the cart that are no longer
available, recalculating all of the discounts, and removing voucher
codes that are no longer available. '''
# Fix vouchers first (this affects available discounts)
to_remove = []
for voucher in self.cart.vouchers.all():
try:
self._test_voucher(voucher)
except ValidationError:
to_remove.append(voucher)
for voucher in to_remove:
self.cart.vouchers.remove(voucher)
# Fix products and discounts
items = commerce.ProductItem.objects.filter(cart=self.cart)
items = items.select_related("product")
products = set(i.product for i in items)
available = set(ProductController.available_products(
self.cart.user,
products=products,
))
not_available = products - available
zeros = [(product, 0) for product in not_available]
self.set_quantities(zeros) |
Calculates all of the discounts available for this product. | def _recalculate_discounts(self):
''' Calculates all of the discounts available for this product.'''
# Delete the existing entries.
commerce.DiscountItem.objects.filter(cart=self.cart).delete()
# Order the products such that the most expensive ones are
# processed first.
product_items = self.cart.productitem_set.all().select_related(
"product", "product__category"
).order_by("-product__price")
products = [i.product for i in product_items]
discounts = DiscountController.available_discounts(
self.cart.user,
[],
products,
)
# The highest-value discounts will apply to the highest-value
# products first, because of the order_by clause
for item in product_items:
self._add_discount(item.product, item.quantity, discounts) |
Applies the best discounts on the given product from the given discounts. | def _add_discount(self, product, quantity, discounts):
''' Applies the best discounts on the given product, from the given
discounts.'''
def matches(discount):
''' Returns True if and only if the given discount apples to
our product. '''
if isinstance(discount.clause, conditions.DiscountForCategory):
return discount.clause.category == product.category
else:
return discount.clause.product == product
def value(discount):
''' Returns the value of this discount clause
as applied to this product '''
if discount.clause.percentage is not None:
return discount.clause.percentage * product.price
else:
return discount.clause.price
discounts = [i for i in discounts if matches(i)]
discounts.sort(key=value)
for candidate in reversed(discounts):
if quantity == 0:
break
elif candidate.quantity == 0:
# This discount clause has been exhausted by this cart
continue
# Get a provisional instance for this DiscountItem
# with the quantity set to as much as we have in the cart
discount_item = commerce.DiscountItem.objects.create(
product=product,
cart=self.cart,
discount=candidate.discount,
quantity=quantity,
)
# Truncate the quantity for this DiscountItem if we exceed quantity
ours = discount_item.quantity
allowed = candidate.quantity
if ours > allowed:
discount_item.quantity = allowed
discount_item.save()
# Update the remaining quantity.
quantity = ours - allowed
else:
quantity = 0
candidate.quantity -= discount_item.quantity |
Decorator that converts a report view function into something that displays a Report. | def report_view(title, form_type=None):
''' Decorator that converts a report view function into something that
displays a Report.
Arguments:
title (str):
The title of the report.
form_type (Optional[forms.Form]):
A form class that can make this report display things. If not
supplied, no form will be displayed.
'''
# Create & return view
def _report(view):
report_view = ReportView(view, title, form_type)
report_view = user_passes_test(views._staff_only)(report_view)
report_view = wraps(view)(report_view)
# Add this report to the list of reports.
_all_report_views.append(report_view)
return report_view
return _report |
Returns the data rows for the table. | def rows(self, content_type):
''' Returns the data rows for the table. '''
for row in self._data:
yield [
self.cell_text(content_type, i, cell)
for i, cell in enumerate(row)
] |
Creates an instance of self. form_type using request. GET | def get_form(self, request):
''' Creates an instance of self.form_type using request.GET '''
# Create a form instance
if self.form_type is not None:
form = self.form_type(request.GET)
# Pre-validate it
form.is_valid()
else:
form = None
return form |
Wraps the reports in a _ReportTemplateWrapper for the given content_type -- this allows data to be returned as HTML links for instance. | def wrap_reports(cls, reports, content_type):
''' Wraps the reports in a _ReportTemplateWrapper for the given
content_type -- this allows data to be returned as HTML links, for
instance. '''
reports = [
_ReportTemplateWrapper(content_type, report)
for report in reports
]
return reports |
Renders the reports based on data. content_type s value. | def render(self, data):
''' Renders the reports based on data.content_type's value.
Arguments:
data (ReportViewRequestData): The report data. data.content_type
is used to determine how the reports are rendered.
Returns:
HTTPResponse: The rendered version of the report.
'''
renderers = {
"text/csv": self._render_as_csv,
"text/html": self._render_as_html,
None: self._render_as_html,
}
render = renderers[data.content_type]
return render(data) |
Lists all of the reports currently available. | def reports_list(request):
''' Lists all of the reports currently available. '''
reports = []
for report in get_all_reports():
reports.append({
"name": report.__name__,
"url": reverse(report),
"description": report.__doc__,
})
reports.sort(key=lambda report: report["name"])
ctx = {
"reports": reports,
}
return render(request, "registrasion/reports_list.html", ctx) |
Summarises the items sold and discounts granted for a given set of products or products from categories. | def items_sold():
''' Summarises the items sold and discounts granted for a given set of
products, or products from categories. '''
data = None
headings = None
line_items = commerce.LineItem.objects.filter(
invoice__status=commerce.Invoice.STATUS_PAID,
).select_related("invoice")
line_items = line_items.order_by(
# sqlite requires an order_by for .values() to work
"-price", "description",
).values(
"price", "description",
).annotate(
total_quantity=Sum("quantity"),
)
headings = ["Description", "Quantity", "Price", "Total"]
data = []
total_income = 0
for line in line_items:
cost = line["total_quantity"] * line["price"]
data.append([
line["description"], line["total_quantity"],
line["price"], cost,
])
total_income += cost
data.append([
"(TOTAL)", "--", "--", total_income,
])
return ListReport("Items sold", headings, data) |
Summarises paid items and payments. | def sales_payment_summary():
''' Summarises paid items and payments. '''
def value_or_zero(aggregate, key):
return aggregate[key] or 0
def sum_amount(payment_set):
a = payment_set.values("amount").aggregate(total=Sum("amount"))
return value_or_zero(a, "total")
headings = ["Category", "Total"]
data = []
# Summarise all sales made (= income.)
sales = commerce.LineItem.objects.filter(
invoice__status=commerce.Invoice.STATUS_PAID,
).values(
"price", "quantity"
).aggregate(
total=Sum(F("price") * F("quantity"), output_field=CURRENCY()),
)
sales = value_or_zero(sales, "total")
all_payments = sum_amount(commerce.PaymentBase.objects.all())
# Manual payments
# Credit notes generated (total)
# Payments made by credit note
# Claimed credit notes
all_credit_notes = 0 - sum_amount(commerce.CreditNote.objects.all())
unclaimed_credit_notes = 0 - sum_amount(commerce.CreditNote.unclaimed())
claimed_credit_notes = sum_amount(
commerce.CreditNoteApplication.objects.all()
)
refunded_credit_notes = 0 - sum_amount(commerce.CreditNote.refunded())
data.append(["Items on paid invoices", sales])
data.append(["All payments", all_payments])
data.append(["Sales - Payments ", sales - all_payments])
data.append(["All credit notes", all_credit_notes])
data.append(["Credit notes paid on invoices", claimed_credit_notes])
data.append(["Credit notes refunded", refunded_credit_notes])
data.append(["Unclaimed credit notes", unclaimed_credit_notes])
data.append([
"Credit notes - (claimed credit notes + unclaimed credit notes)",
all_credit_notes - claimed_credit_notes -
refunded_credit_notes - unclaimed_credit_notes
])
return ListReport("Sales and Payments Summary", headings, data) |
Shows the history of payments into the system | def payments():
''' Shows the history of payments into the system '''
payments = commerce.PaymentBase.objects.all()
return QuerysetReport(
"Payments",
["invoice__id", "id", "reference", "amount"],
payments,
link_view=views.invoice,
) |
Shows all of the credit notes that have been generated. | def credit_note_refunds():
''' Shows all of the credit notes that have been generated. '''
notes_refunded = commerce.CreditNote.refunded()
return QuerysetReport(
"Credit note refunds",
["id", "creditnoterefund__reference", "amount"],
notes_refunded,
link_view=views.credit_note,
) |
Summarises the inventory status of the given items grouping by invoice status. | def product_status(request, form):
''' Summarises the inventory status of the given items, grouping by
invoice status. '''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
items = commerce.ProductItem.objects.filter(
Q(product__in=products) | Q(product__category__in=categories),
).select_related("cart", "product")
items = group_by_cart_status(
items,
["product__category__order", "product__order"],
["product", "product__category__name", "product__name"],
)
headings = [
"Product", "Paid", "Reserved", "Unreserved", "Refunded",
]
data = []
for item in items:
data.append([
"%s - %s" % (
item["product__category__name"], item["product__name"]
),
item["total_paid"],
item["total_reserved"],
item["total_unreserved"],
item["total_refunded"],
])
return ListReport("Inventory", headings, data) |
Summarises the usage of a given discount. | def discount_status(request, form):
''' Summarises the usage of a given discount. '''
discounts = form.cleaned_data["discount"]
items = commerce.DiscountItem.objects.filter(
Q(discount__in=discounts),
).select_related("cart", "product", "product__category")
items = group_by_cart_status(
items,
["discount"],
["discount", "discount__description"],
)
headings = [
"Discount", "Paid", "Reserved", "Unreserved", "Refunded",
]
data = []
for item in items:
data.append([
item["discount__description"],
item["total_paid"],
item["total_reserved"],
item["total_unreserved"],
item["total_refunded"],
])
return ListReport("Usage by item", headings, data) |
Shows each product line item from invoices including their date and purchashing customer. | def product_line_items(request, form):
''' Shows each product line item from invoices, including their date and
purchashing customer. '''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
invoices = commerce.Invoice.objects.filter(
(
Q(lineitem__product__in=products) |
Q(lineitem__product__category__in=categories)
),
status=commerce.Invoice.STATUS_PAID,
).select_related(
"cart",
"user",
"user__attendee",
"user__attendee__attendeeprofilebase"
).order_by("issue_time")
headings = [
'Invoice', 'Invoice Date', 'Attendee', 'Qty', 'Product', 'Status'
]
data = []
for invoice in invoices:
for item in invoice.cart.productitem_set.all():
if item.product in products or item.product.category in categories:
output = []
output.append(invoice.id)
output.append(invoice.issue_time.strftime('%Y-%m-%d %H:%M:%S'))
output.append(
invoice.user.attendee.attendeeprofilebase.attendee_name()
)
output.append(item.quantity)
output.append(item.product)
cart = invoice.cart
if cart.status == commerce.Cart.STATUS_PAID:
output.append('PAID')
elif cart.status == commerce.Cart.STATUS_ACTIVE:
output.append('UNPAID')
elif cart.status == commerce.Cart.STATUS_RELEASED:
output.append('REFUNDED')
data.append(output)
return ListReport("Line Items", headings, data) |
Shows the number of paid invoices containing given products or categories per day. | def paid_invoices_by_date(request, form):
''' Shows the number of paid invoices containing given products or
categories per day. '''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
invoices = commerce.Invoice.objects.filter(
(
Q(lineitem__product__in=products) |
Q(lineitem__product__category__in=categories)
),
status=commerce.Invoice.STATUS_PAID,
)
# Invoices with payments will be paid at the time of their latest payment
payments = commerce.PaymentBase.objects.all()
payments = payments.filter(
invoice__in=invoices,
)
payments = payments.order_by("invoice")
invoice_max_time = payments.values("invoice").annotate(
max_time=Max("time")
)
# Zero-value invoices will have no payments, so they're paid at issue time
zero_value_invoices = invoices.filter(value=0)
times = itertools.chain(
(line["max_time"] for line in invoice_max_time),
(invoice.issue_time for invoice in zero_value_invoices),
)
by_date = collections.defaultdict(int)
for time in times:
date = datetime.datetime(
year=time.year, month=time.month, day=time.day
)
by_date[date] += 1
data = [(date_, count) for date_, count in sorted(by_date.items())]
data = [(date_.strftime("%Y-%m-%d"), count) for date_, count in data]
return ListReport(
"Paid Invoices By Date",
["date", "count"],
data,
) |
Shows all of the credit notes in the system. | def credit_notes(request, form):
''' Shows all of the credit notes in the system. '''
notes = commerce.CreditNote.objects.all().select_related(
"creditnoterefund",
"creditnoteapplication",
"invoice",
"invoice__user__attendee__attendeeprofilebase",
)
return QuerysetReport(
"Credit Notes",
["id",
"invoice__user__attendee__attendeeprofilebase__invoice_recipient",
"status", "value"],
notes,
headings=["id", "Owner", "Status", "Value"],
link_view=views.credit_note,
) |
Shows all of the invoices in the system. | def invoices(request, form):
''' Shows all of the invoices in the system. '''
invoices = commerce.Invoice.objects.all().order_by("status", "id")
return QuerysetReport(
"Invoices",
["id", "recipient", "value", "get_status_display"],
invoices,
headings=["id", "Recipient", "Value", "Status"],
link_view=views.invoice,
) |
Returns a list of all manifested attendees if no attendee is specified else displays the attendee manifest. | def attendee(request, form, user_id=None):
''' Returns a list of all manifested attendees if no attendee is specified,
else displays the attendee manifest. '''
if user_id is None and form.cleaned_data["user"] is not None:
user_id = form.cleaned_data["user"]
if user_id is None:
return attendee_list(request)
attendee = people.Attendee.objects.get(user__id=user_id)
name = attendee.attendeeprofilebase.attendee_name()
reports = []
profile_data = []
try:
profile = people.AttendeeProfileBase.objects.get_subclass(
attendee=attendee
)
fields = profile._meta.get_fields()
except people.AttendeeProfileBase.DoesNotExist:
fields = []
exclude = set(["attendeeprofilebase_ptr", "id"])
for field in fields:
if field.name in exclude:
# Not actually important
continue
if not hasattr(field, "verbose_name"):
continue # Not a publicly visible field
value = getattr(profile, field.name)
if isinstance(field, models.ManyToManyField):
value = ", ".join(str(i) for i in value.all())
profile_data.append((field.verbose_name, value))
cart = CartController.for_user(attendee.user)
reservation = cart.cart.reservation_duration + cart.cart.time_last_updated
profile_data.append(("Current cart reserved until", reservation))
reports.append(ListReport("Profile", ["", ""], profile_data))
links = []
links.append((
reverse(views.badge, args=[user_id]),
"View badge",
))
links.append((
reverse(views.amend_registration, args=[user_id]),
"Amend current cart",
))
links.append((
reverse(views.extend_reservation, args=[user_id]),
"Extend reservation",
))
reports.append(Links("Actions for " + name, links))
# Paid and pending products
ic = ItemController(attendee.user)
reports.append(ListReport(
"Paid Products",
["Product", "Quantity"],
[(pq.product, pq.quantity) for pq in ic.items_purchased()],
))
reports.append(ListReport(
"Unpaid Products",
["Product", "Quantity"],
[(pq.product, pq.quantity) for pq in ic.items_pending()],
))
# Invoices
invoices = commerce.Invoice.objects.filter(
user=attendee.user,
)
reports.append(QuerysetReport(
"Invoices",
["id", "get_status_display", "value"],
invoices,
headings=["Invoice ID", "Status", "Value"],
link_view=views.invoice,
))
# Credit Notes
credit_notes = commerce.CreditNote.objects.filter(
invoice__user=attendee.user,
).select_related("invoice", "creditnoteapplication", "creditnoterefund")
reports.append(QuerysetReport(
"Credit Notes",
["id", "status", "value"],
credit_notes,
link_view=views.credit_note,
))
# All payments
payments = commerce.PaymentBase.objects.filter(
invoice__user=attendee.user,
).select_related("invoice")
reports.append(QuerysetReport(
"Payments",
["invoice__id", "id", "reference", "amount"],
payments,
link_view=views.invoice,
))
return reports |
Returns a list of all attendees. | def attendee_list(request):
''' Returns a list of all attendees. '''
attendees = people.Attendee.objects.select_related(
"attendeeprofilebase",
"user",
)
profiles = AttendeeProfile.objects.filter(
attendee__in=attendees
).select_related(
"attendee", "attendee__user",
)
profiles_by_attendee = dict((i.attendee, i) for i in profiles)
attendees = attendees.annotate(
has_registered=Count(
Q(user__invoice__status=commerce.Invoice.STATUS_PAID)
),
)
headings = [
"User ID", "Name", "Email", "Has registered",
]
data = []
for a in attendees:
data.append([
a.user.id,
(profiles_by_attendee[a].attendee_name()
if a in profiles_by_attendee else ""),
a.user.email,
a.has_registered > 0,
])
# Sort by whether they've registered, then ID.
data.sort(key=lambda a: (-a[3], a[0]))
return AttendeeListReport("Attendees", headings, data, link_view=attendee) |
Lists attendees for a given product/ category selection along with profile data. | def attendee_data(request, form, user_id=None):
''' Lists attendees for a given product/category selection along with
profile data.'''
status_display = {
commerce.Cart.STATUS_ACTIVE: "Unpaid",
commerce.Cart.STATUS_PAID: "Paid",
commerce.Cart.STATUS_RELEASED: "Refunded",
}
output = []
by_category = (
form.cleaned_data["group_by"] == forms.GroupByForm.GROUP_BY_CATEGORY)
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
fields = form.cleaned_data["fields"]
name_field = AttendeeProfile.name_field()
items = commerce.ProductItem.objects.filter(
Q(product__in=products) | Q(product__category__in=categories),
).exclude(
cart__status=commerce.Cart.STATUS_RELEASED
).select_related(
"cart", "cart__user", "product", "product__category",
).order_by("cart__status")
# Add invoice nag link
links = []
invoice_mailout = reverse(views.invoice_mailout, args=[])
invoice_mailout += "?" + request.META["QUERY_STRING"]
links += [
(invoice_mailout + "&status=1", "Send invoice reminders",),
(invoice_mailout + "&status=2", "Send mail for paid invoices",),
]
if items.count() > 0:
output.append(Links("Actions", links))
# Make sure we select all of the related fields
related_fields = set(
field for field in fields
if isinstance(AttendeeProfile._meta.get_field(field), RelatedField)
)
# Get all of the relevant attendee profiles in one hit.
profiles = AttendeeProfile.objects.filter(
attendee__user__cart__productitem__in=items
).select_related("attendee__user").prefetch_related(*related_fields)
by_user = {}
for profile in profiles:
by_user[profile.attendee.user] = profile
cart = "attendee__user__cart"
cart_status = cart + "__status" # noqa
product = cart + "__productitem__product"
product_name = product + "__name"
category = product + "__category"
category_name = category + "__name"
if by_category:
grouping_fields = (category, category_name)
order_by = (category, )
first_column = "Category"
group_name = lambda i: "%s" % (i[category_name], ) # noqa
else:
grouping_fields = (product, product_name, category_name)
order_by = (category, )
first_column = "Product"
group_name = lambda i: "%s - %s" % (i[category_name], i[product_name]) # noqa
# Group the responses per-field.
for field in fields:
concrete_field = AttendeeProfile._meta.get_field(field)
field_verbose = concrete_field.verbose_name
# Render the correct values for related fields
if field in related_fields:
# Get all of the IDs that will appear
all_ids = profiles.order_by(field).values(field)
all_ids = [i[field] for i in all_ids if i[field] is not None]
# Get all of the concrete objects for those IDs
model = concrete_field.related_model
all_objects = model.objects.filter(id__in=all_ids)
all_objects_by_id = dict((i.id, i) for i in all_objects)
# Define a function to render those IDs.
def display_field(value):
if value in all_objects_by_id:
return all_objects_by_id[value]
else:
return None
else:
def display_field(value):
return value
status_count = lambda status: Case(When( # noqa
attendee__user__cart__status=status,
then=Value(1),
),
default=Value(0),
output_field=models.fields.IntegerField(),
)
paid_count = status_count(commerce.Cart.STATUS_PAID)
unpaid_count = status_count(commerce.Cart.STATUS_ACTIVE)
groups = profiles.order_by(
*(order_by + (field, ))
).values(
*(grouping_fields + (field, ))
).annotate(
paid_count=Sum(paid_count),
unpaid_count=Sum(unpaid_count),
)
output.append(ListReport(
"Grouped by %s" % field_verbose,
[first_column, field_verbose, "paid", "unpaid"],
[
(
group_name(group),
display_field(group[field]),
group["paid_count"] or 0,
group["unpaid_count"] or 0,
)
for group in groups
],
))
# DO the report for individual attendees
field_names = [
AttendeeProfile._meta.get_field(field).verbose_name for field in fields
]
def display_field(profile, field):
field_type = AttendeeProfile._meta.get_field(field)
attr = getattr(profile, field)
if isinstance(field_type, models.ManyToManyField):
return [str(i) for i in attr.all()] or ""
else:
return attr
headings = ["User ID", "Name", "Email", "Product", "Item Status"]
headings.extend(field_names)
data = []
for item in items:
profile = by_user[item.cart.user]
line = [
item.cart.user.id,
getattr(profile, name_field),
profile.attendee.user.email,
item.product,
status_display[item.cart.status],
] + [
display_field(profile, field) for field in fields
]
data.append(line)
output.append(AttendeeListReport(
"Attendees by item with profile data", headings, data,
link_view=attendee
))
return output |
Shows registration status for speakers with a given proposal kind. | def speaker_registrations(request, form):
''' Shows registration status for speakers with a given proposal kind. '''
kinds = form.cleaned_data["kind"]
presentations = schedule_models.Presentation.objects.filter(
proposal_base__kind__in=kinds,
).exclude(
cancelled=True,
)
users = User.objects.filter(
Q(speaker_profile__presentations__in=presentations) |
Q(speaker_profile__copresentations__in=presentations)
)
paid_carts = commerce.Cart.objects.filter(status=commerce.Cart.STATUS_PAID)
paid_carts = Case(
When(cart__in=paid_carts, then=Value(1)),
default=Value(0),
output_field=models.IntegerField(),
)
users = users.annotate(paid_carts=Sum(paid_carts))
users = users.order_by("paid_carts")
return QuerysetReport(
"Speaker Registration Status",
["id", "speaker_profile__name", "email", "paid_carts"],
users,
link_view=attendee,
)
return [] |
Produces the registration manifest for people with the given product type. | def manifest(request, form):
'''
Produces the registration manifest for people with the given product
type.
'''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
line_items = (
Q(lineitem__product__in=products) |
Q(lineitem__product__category__in=categories)
)
invoices = commerce.Invoice.objects.filter(
line_items,
status=commerce.Invoice.STATUS_PAID,
).select_related(
"cart",
"user",
"user__attendee",
"user__attendee__attendeeprofilebase"
)
users = set(i.user for i in invoices)
carts = commerce.Cart.objects.filter(
user__in=users
)
items = commerce.ProductItem.objects.filter(
cart__in=carts
).select_related(
"product",
"product__category",
"cart",
"cart__user",
"cart__user__attendee",
"cart__user__attendee__attendeeprofilebase"
).order_by("product__category__order", "product__order")
users = {}
for item in items:
cart = item.cart
if cart.user not in users:
users[cart.user] = {"unpaid": [], "paid": [], "refunded": []}
items = users[cart.user]
if cart.status == commerce.Cart.STATUS_ACTIVE:
items["unpaid"].append(item)
elif cart.status == commerce.Cart.STATUS_PAID:
items["paid"].append(item)
elif cart.status == commerce.Cart.STATUS_RELEASED:
items["refunded"].append(item)
users_by_name = list(users.keys())
users_by_name.sort(key=(
lambda i: i.attendee.attendeeprofilebase.attendee_name().lower()
))
headings = ["User ID", "Name", "Paid", "Unpaid", "Refunded"]
def format_items(item_list):
strings = [
'%d x %s' % (item.quantity, str(item.product))
for item in item_list
]
return ", \n".join(strings)
output = []
for user in users_by_name:
items = users[user]
output.append([
user.id,
user.attendee.attendeeprofilebase.attendee_name(),
format_items(items["paid"]),
format_items(items["unpaid"]),
format_items(items["refunded"]),
])
return ListReport("Manifest", headings, output) |
Adds the categories that the user does not currently have. | def missing_categories(context):
''' Adds the categories that the user does not currently have. '''
user = user_for_context(context)
categories_available = set(CategoryController.available_categories(user))
items = ItemController(user).items_pending_or_purchased()
categories_held = set()
for product, quantity in items:
categories_held.add(product.category)
return categories_available - categories_held |
Calculates the sum of unclaimed credit from this user s credit notes. | def available_credit(context):
''' Calculates the sum of unclaimed credit from this user's credit notes.
Returns:
Decimal: the sum of the values of unclaimed credit notes for the
current user.
'''
notes = commerce.CreditNote.unclaimed().filter(
invoice__user=user_for_context(context),
)
ret = notes.values("amount").aggregate(Sum("amount"))["amount__sum"] or 0
return 0 - ret |
Returns the number of items purchased for this user ( sum of quantities ). | def total_items_purchased(context, category=None):
''' Returns the number of items purchased for this user (sum of quantities).
The user will be either `context.user`, and `context.request.user` if
the former is not defined.
'''
return sum(i.quantity for i in items_purchased(context, category)) |
If the current user is unregistered returns True if there are no products in the TICKET_PRODUCT_CATEGORY that are available to that user. | def sold_out_and_unregistered(context):
''' If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then return None (it's not a
pertinent question for people who already have a ticket).
'''
user = user_for_context(context)
if hasattr(user, "attendee") and user.attendee.completed_registration:
# This user has completed registration, and so we don't need to answer
# whether they have sold out yet.
# TODO: what if a user has got to the review phase?
# currently that user will hit the review page, click "Check out and
# pay", and that will fail. Probably good enough for now.
return None
ticket_category = settings.TICKET_PRODUCT_CATEGORY
categories = available_categories(context)
return ticket_category not in [cat.id for cat in categories] |
Usage: { % include_if_exists head. html % } | def include_if_exists(parser, token):
"""Usage: {% include_if_exists "head.html" %}
This will fail silently if the template doesn't exist. If it does, it will
be rendered with the current context.
From: https://djangosnippets.org/snippets/2058/
"""
try:
tag_name, template_name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, \
"%r tag requires a single argument" % token.contents.split()[0]
return IncludeNode(template_name) |
Goes through the registration process in order making sure user sees all valid categories. | def guided_registration(request, page_number=None):
''' Goes through the registration process in order, making sure user sees
all valid categories.
The user must be logged in to see this view.
Parameter:
page_number:
1) Profile form (and e-mail address?)
2) Ticket type
3) Remaining products
4) Mark registration as complete
Returns:
render: Renders ``registrasion/guided_registration.html``,
with the following data::
{
"current_step": int(), # The current step in the
# registration
"sections": sections, # A list of
# GuidedRegistrationSections
"title": str(), # The title of the page
"total_steps": int(), # The total number of steps
}
'''
PAGE_PROFILE = 1
PAGE_TICKET = 2
PAGE_PRODUCTS = 3
PAGE_PRODUCTS_MAX = 4
TOTAL_PAGES = 4
ticket_category = inventory.Category.objects.get(
id=settings.TICKET_PRODUCT_CATEGORY
)
cart = CartController.for_user(request.user)
attendee = people.Attendee.get_instance(request.user)
# This guided registration process is only for people who have
# not completed registration (and has confusing behaviour if you go
# back to it.)
if attendee.completed_registration:
return redirect(review)
# Calculate the current maximum page number for this user.
has_profile = hasattr(attendee, "attendeeprofilebase")
if not has_profile:
# If there's no profile, they have to go to the profile page.
max_page = PAGE_PROFILE
redirect_page = PAGE_PROFILE
else:
# We have a profile.
# Do they have a ticket?
products = inventory.Product.objects.filter(
productitem__cart=cart.cart
)
products = products.filter(category=ticket_category)
if products.count() == 0:
# If no ticket, they can only see the profile or ticket page.
max_page = PAGE_TICKET
redirect_page = PAGE_TICKET
else:
# If there's a ticket, they should *see* the general products page#
# but be able to go to the overflow page if needs be.
max_page = PAGE_PRODUCTS_MAX
redirect_page = PAGE_PRODUCTS
if page_number is None or int(page_number) > max_page:
return redirect("guided_registration", redirect_page)
page_number = int(page_number)
next_step = redirect("guided_registration", page_number + 1)
with BatchController.batch(request.user):
# This view doesn't work if the conference has sold out.
available = ProductController.available_products(
request.user, category=ticket_category
)
if not available:
messages.error(request, "There are no more tickets available.")
return redirect("dashboard")
sections = []
# Build up the list of sections
if page_number == PAGE_PROFILE:
# Profile bit
title = "Attendee information"
sections = _guided_registration_profile_and_voucher(request)
elif page_number == PAGE_TICKET:
# Select ticket
title = "Select ticket type"
sections = _guided_registration_products(
request, GUIDED_MODE_TICKETS_ONLY
)
elif page_number == PAGE_PRODUCTS:
# Select additional items
title = "Additional items"
sections = _guided_registration_products(
request, GUIDED_MODE_ALL_ADDITIONAL
)
elif page_number == PAGE_PRODUCTS_MAX:
# Items enabled by things on page 3 -- only shows things
# that have not been marked as complete.
title = "More additional items"
sections = _guided_registration_products(
request, GUIDED_MODE_EXCLUDE_COMPLETE
)
if not sections:
# We've filled in every category
attendee.completed_registration = True
attendee.save()
return redirect("review")
if sections and request.method == "POST":
for section in sections:
if section.form.errors:
break
else:
# We've successfully processed everything
return next_step
data = {
"current_step": page_number,
"sections": sections,
"title": title,
"total_steps": TOTAL_PAGES,
}
return render(request, "registrasion/guided_registration.html", data) |
View for editing an attendee s profile | def edit_profile(request):
''' View for editing an attendee's profile
The user must be logged in to edit their profile.
Returns:
redirect or render:
In the case of a ``POST`` request, it'll redirect to ``dashboard``,
or otherwise, it will render ``registrasion/profile_form.html``
with data::
{
"form": form, # Instance of ATTENDEE_PROFILE_FORM.
}
'''
form, handled = _handle_profile(request, "profile")
if handled and not form.errors:
messages.success(
request,
"Your attendee profile was updated.",
)
return redirect("dashboard")
data = {
"form": form,
}
return render(request, "registrasion/profile_form.html", data) |
Returns a profile form instance and a boolean which is true if the form was handled. | def _handle_profile(request, prefix):
''' Returns a profile form instance, and a boolean which is true if the
form was handled. '''
attendee = people.Attendee.get_instance(request.user)
try:
profile = attendee.attendeeprofilebase
profile = people.AttendeeProfileBase.objects.get_subclass(
pk=profile.id,
)
except ObjectDoesNotExist:
profile = None
# Load a pre-entered name from the speaker's profile,
# if they have one.
try:
speaker_profile = request.user.speaker_profile
speaker_name = speaker_profile.name
except ObjectDoesNotExist:
speaker_name = None
name_field = ProfileForm.Meta.model.name_field()
initial = {}
if profile is None and name_field is not None:
initial[name_field] = speaker_name
form = ProfileForm(
request.POST or None,
initial=initial,
instance=profile,
prefix=prefix
)
handled = True if request.POST else False
if request.POST and form.is_valid():
form.instance.attendee = attendee
form.save()
return form, handled |
Form for selecting products from an individual product category. | def product_category(request, category_id):
''' Form for selecting products from an individual product category.
Arguments:
category_id (castable to int): The id of the category to display.
Returns:
redirect or render:
If the form has been sucessfully submitted, redirect to
``dashboard``. Otherwise, render
``registrasion/product_category.html`` with data::
{
"category": category, # An inventory.Category for
# category_id
"discounts": discounts, # A list of
# DiscountAndQuantity
"form": products_form, # A form for selecting
# products
"voucher_form": voucher_form, # A form for entering a
# voucher code
}
'''
PRODUCTS_FORM_PREFIX = "products"
VOUCHERS_FORM_PREFIX = "vouchers"
# Handle the voucher form *before* listing products.
# Products can change as vouchers are entered.
v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)
voucher_form, voucher_handled = v
category_id = int(category_id) # Routing is [0-9]+
category = inventory.Category.objects.get(pk=category_id)
with BatchController.batch(request.user):
products = ProductController.available_products(
request.user,
category=category,
)
if not products:
messages.warning(
request,
(
"There are no products available from category: " +
category.name
),
)
return redirect("dashboard")
p = _handle_products(request, category, products, PRODUCTS_FORM_PREFIX)
products_form, discounts, products_handled = p
if request.POST and not voucher_handled and not products_form.errors:
# Only return to the dashboard if we didn't add a voucher code
# and if there's no errors in the products form
if products_form.has_changed():
messages.success(
request,
"Your reservations have been updated.",
)
return redirect(review)
data = {
"category": category,
"discounts": discounts,
"form": products_form,
"voucher_form": voucher_form,
}
return render(request, "registrasion/product_category.html", data) |
A view * just * for entering a voucher form. | def voucher_code(request):
''' A view *just* for entering a voucher form. '''
VOUCHERS_FORM_PREFIX = "vouchers"
# Handle the voucher form *before* listing products.
# Products can change as vouchers are entered.
v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)
voucher_form, voucher_handled = v
if voucher_handled:
messages.success(request, "Your voucher code was accepted.")
return redirect("dashboard")
data = {
"voucher_form": voucher_form,
}
return render(request, "registrasion/voucher_code.html", data) |
Handles a products list form in the given request. Returns the form instance the discounts applicable to this form and whether the contents were handled. | def _handle_products(request, category, products, prefix):
''' Handles a products list form in the given request. Returns the
form instance, the discounts applicable to this form, and whether the
contents were handled. '''
current_cart = CartController.for_user(request.user)
ProductsForm = forms.ProductsForm(category, products)
# Create initial data for each of products in category
items = commerce.ProductItem.objects.filter(
product__in=products,
cart=current_cart.cart,
).select_related("product")
quantities = []
seen = set()
for item in items:
quantities.append((item.product, item.quantity))
seen.add(item.product)
zeros = set(products) - seen
for product in zeros:
quantities.append((product, 0))
products_form = ProductsForm(
request.POST or None,
product_quantities=quantities,
prefix=prefix,
)
if request.method == "POST" and products_form.is_valid():
if products_form.has_changed():
_set_quantities_from_products_form(products_form, current_cart)
# If category is required, the user must have at least one
# in an active+valid cart
if category.required:
carts = commerce.Cart.objects.filter(user=request.user)
items = commerce.ProductItem.objects.filter(
product__category=category,
cart=carts,
)
if len(items) == 0:
products_form.add_error(
None,
"You must have at least one item from this category",
)
handled = False if products_form.errors else True
# Making this a function to lazily evaluate when it's displayed
# in templates.
discounts = util.lazy(
DiscountController.available_discounts,
request.user,
[],
products,
)
return products_form, discounts, handled |
Handles a voucher form in the given request. Returns the voucher form instance and whether the voucher code was handled. | def _handle_voucher(request, prefix):
''' Handles a voucher form in the given request. Returns the voucher
form instance, and whether the voucher code was handled. '''
voucher_form = forms.VoucherForm(request.POST or None, prefix=prefix)
current_cart = CartController.for_user(request.user)
if (voucher_form.is_valid() and
voucher_form.cleaned_data["voucher"].strip()):
voucher = voucher_form.cleaned_data["voucher"]
voucher = inventory.Voucher.normalise_code(voucher)
if len(current_cart.cart.vouchers.filter(code=voucher)) > 0:
# This voucher has already been applied to this cart.
# Do not apply code
handled = False
else:
try:
current_cart.apply_voucher(voucher)
except Exception as e:
voucher_form.add_error("voucher", e)
handled = True
else:
handled = False
return (voucher_form, handled) |
Runs the checkout process for the current cart. | def checkout(request, user_id=None):
''' Runs the checkout process for the current cart.
If the query string contains ``fix_errors=true``, Registrasion will attempt
to fix errors preventing the system from checking out, including by
cancelling expired discounts and vouchers, and removing any unavailable
products.
Arguments:
user_id (castable to int):
If the requesting user is staff, then the user ID can be used to
run checkout for another user.
Returns:
render or redirect:
If the invoice is generated successfully, or there's already a
valid invoice for the current cart, redirect to ``invoice``.
If there are errors when generating the invoice, render
``registrasion/checkout_errors.html`` with the following data::
{
"error_list", [str, ...] # The errors to display.
}
'''
if user_id is not None:
if request.user.is_staff:
user = User.objects.get(id=int(user_id))
else:
raise Http404()
else:
user = request.user
current_cart = CartController.for_user(user)
if "fix_errors" in request.GET and request.GET["fix_errors"] == "true":
current_cart.fix_simple_errors()
try:
current_invoice = InvoiceController.for_cart(current_cart.cart)
except ValidationError as ve:
return _checkout_errors(request, ve)
return redirect("invoice", current_invoice.invoice.id) |
Redirects to an invoice for the attendee that matches the given access code if any. | def invoice_access(request, access_code):
''' Redirects to an invoice for the attendee that matches the given access
code, if any.
If the attendee has multiple invoices, we use the following tie-break:
- If there's an unpaid invoice, show that, otherwise
- If there's a paid invoice, show the most recent one, otherwise
- Show the most recent invoid of all
Arguments:
access_code (castable to int): The access code for the user whose
invoice you want to see.
Returns:
redirect:
Redirect to the selected invoice for that user.
Raises:
Http404: If the user has no invoices.
'''
invoices = commerce.Invoice.objects.filter(
user__attendee__access_code=access_code,
).order_by("-issue_time")
if not invoices:
raise Http404()
unpaid = invoices.filter(status=commerce.Invoice.STATUS_UNPAID)
paid = invoices.filter(status=commerce.Invoice.STATUS_PAID)
if unpaid:
invoice = unpaid[0] # (should only be 1 unpaid invoice?)
elif paid:
invoice = paid[0] # Most recent paid invoice
else:
invoice = invoices[0] # Most recent of any invoices
return redirect("invoice", invoice.id, access_code) |
Displays an invoice. | def invoice(request, invoice_id, access_code=None):
''' Displays an invoice.
This view is not authenticated, but it will only allow access to either:
the user the invoice belongs to; staff; or a request made with the correct
access code.
Arguments:
invoice_id (castable to int): The invoice_id for the invoice you want
to view.
access_code (Optional[str]): The access code for the user who owns
this invoice.
Returns:
render:
Renders ``registrasion/invoice.html``, with the following
data::
{
"invoice": models.commerce.Invoice(),
}
Raises:
Http404: if the current user cannot view this invoice and the correct
access_code is not provided.
'''
current_invoice = InvoiceController.for_id_or_404(invoice_id)
if not current_invoice.can_view(
user=request.user,
access_code=access_code,
):
raise Http404()
data = {
"invoice": current_invoice.invoice,
}
return render(request, "registrasion/invoice.html", data) |
Allows staff to make manual payments or refunds on an invoice. | def manual_payment(request, invoice_id):
''' Allows staff to make manual payments or refunds on an invoice.
This form requires a login, and the logged in user needs to be staff.
Arguments:
invoice_id (castable to int): The invoice ID to be paid
Returns:
render:
Renders ``registrasion/manual_payment.html`` with the following
data::
{
"invoice": models.commerce.Invoice(),
"form": form, # A form that saves a ``ManualPayment``
# object.
}
'''
FORM_PREFIX = "manual_payment"
current_invoice = InvoiceController.for_id_or_404(invoice_id)
form = forms.ManualPaymentForm(
request.POST or None,
prefix=FORM_PREFIX,
)
if request.POST and form.is_valid():
form.instance.invoice = current_invoice.invoice
form.instance.entered_by = request.user
form.save()
current_invoice.update_status()
form = forms.ManualPaymentForm(prefix=FORM_PREFIX)
data = {
"invoice": current_invoice.invoice,
"form": form,
}
return render(request, "registrasion/manual_payment.html", data) |
Marks an invoice as refunded and requests a credit note for the full amount paid against the invoice. | def refund(request, invoice_id):
''' Marks an invoice as refunded and requests a credit note for the
full amount paid against the invoice.
This view requires a login, and the logged in user must be staff.
Arguments:
invoice_id (castable to int): The ID of the invoice to refund.
Returns:
redirect:
Redirects to ``invoice``.
'''
current_invoice = InvoiceController.for_id_or_404(invoice_id)
try:
current_invoice.refund()
messages.success(request, "This invoice has been refunded.")
except ValidationError as ve:
messages.error(request, ve)
return redirect("invoice", invoice_id) |
Displays a credit note. | def credit_note(request, note_id, access_code=None):
''' Displays a credit note.
If ``request`` is a ``POST`` request, forms for applying or refunding
a credit note will be processed.
This view requires a login, and the logged in user must be staff.
Arguments:
note_id (castable to int): The ID of the credit note to view.
Returns:
render or redirect:
If the "apply to invoice" form is correctly processed, redirect to
that invoice, otherwise, render ``registration/credit_note.html``
with the following data::
{
"credit_note": models.commerce.CreditNote(),
"apply_form": form, # A form for applying credit note
# to an invoice.
"refund_form": form, # A form for applying a *manual*
# refund of the credit note.
"cancellation_fee_form" : form, # A form for generating an
# invoice with a
# cancellation fee
}
'''
note_id = int(note_id)
current_note = CreditNoteController.for_id_or_404(note_id)
apply_form = forms.ApplyCreditNoteForm(
current_note.credit_note.invoice.user,
request.POST or None,
prefix="apply_note"
)
refund_form = forms.ManualCreditNoteRefundForm(
request.POST or None,
prefix="refund_note"
)
cancellation_fee_form = forms.CancellationFeeForm(
request.POST or None,
prefix="cancellation_fee"
)
if request.POST and apply_form.is_valid():
inv_id = apply_form.cleaned_data["invoice"]
invoice = commerce.Invoice.objects.get(pk=inv_id)
current_note.apply_to_invoice(invoice)
messages.success(
request,
"Applied credit note %d to invoice." % note_id,
)
return redirect("invoice", invoice.id)
elif request.POST and refund_form.is_valid():
refund_form.instance.entered_by = request.user
refund_form.instance.parent = current_note.credit_note
refund_form.save()
messages.success(
request,
"Applied manual refund to credit note."
)
refund_form = forms.ManualCreditNoteRefundForm(
prefix="refund_note",
)
elif request.POST and cancellation_fee_form.is_valid():
percentage = cancellation_fee_form.cleaned_data["percentage"]
invoice = current_note.cancellation_fee(percentage)
messages.success(
request,
"Generated cancellation fee for credit note %d." % note_id,
)
return redirect("invoice", invoice.invoice.id)
data = {
"credit_note": current_note.credit_note,
"apply_form": apply_form,
"refund_form": refund_form,
"cancellation_fee_form": cancellation_fee_form,
}
return render(request, "registrasion/credit_note.html", data) |
Allows staff to amend a user s current registration cart and etc etc. | def amend_registration(request, user_id):
''' Allows staff to amend a user's current registration cart, and etc etc.
'''
user = User.objects.get(id=int(user_id))
current_cart = CartController.for_user(user)
items = commerce.ProductItem.objects.filter(
cart=current_cart.cart,
).select_related("product")
initial = [{"product": i.product, "quantity": i.quantity} for i in items]
StaffProductsFormSet = forms.staff_products_formset_factory(user)
formset = StaffProductsFormSet(
request.POST or None,
initial=initial,
prefix="products",
)
for item, form in zip(items, formset):
queryset = inventory.Product.objects.filter(id=item.product.id)
form.fields["product"].queryset = queryset
voucher_form = forms.VoucherForm(
request.POST or None,
prefix="voucher",
)
if request.POST and formset.is_valid():
pq = [
(f.cleaned_data["product"], f.cleaned_data["quantity"])
for f in formset
if "product" in f.cleaned_data and
f.cleaned_data["product"] is not None
]
try:
current_cart.set_quantities(pq)
return redirect(amend_registration, user_id)
except ValidationError as ve:
for ve_field in ve.error_list:
product, message = ve_field.message
for form in formset:
if "product" not in form.cleaned_data:
# This is the empty form.
continue
if form.cleaned_data["product"] == product:
form.add_error("quantity", message)
if request.POST and voucher_form.has_changed() and voucher_form.is_valid():
try:
current_cart.apply_voucher(voucher_form.cleaned_data["voucher"])
return redirect(amend_registration, user_id)
except ValidationError as ve:
voucher_form.add_error(None, ve)
ic = ItemController(user)
data = {
"user": user,
"paid": ic.items_purchased(),
"cancelled": ic.items_released(),
"form": formset,
"voucher_form": voucher_form,
}
return render(request, "registrasion/amend_registration.html", data) |
Allows staff to extend the reservation on a given user s cart. | def extend_reservation(request, user_id, days=7):
''' Allows staff to extend the reservation on a given user's cart.
'''
user = User.objects.get(id=int(user_id))
cart = CartController.for_user(user)
cart.extend_reservation(datetime.timedelta(days=days))
return redirect(request.META["HTTP_REFERER"]) |
Allows staff to send emails to users based on their invoice status. | def invoice_mailout(request):
''' Allows staff to send emails to users based on their invoice status. '''
category = request.GET.getlist("category", [])
product = request.GET.getlist("product", [])
status = request.GET.get("status")
form = forms.InvoiceEmailForm(
request.POST or None,
category=category,
product=product,
status=status,
)
emails = []
if form.is_valid():
emails = []
for invoice in form.cleaned_data["invoice"]:
# datatuple = (subject, message, from_email, recipient_list)
from_email = form.cleaned_data["from_email"]
subject = form.cleaned_data["subject"]
body = Template(form.cleaned_data["body"]).render(
Context({
"invoice": invoice,
"user": invoice.user,
})
)
recipient_list = [invoice.user.email]
emails.append(Email(subject, body, from_email, recipient_list))
if form.cleaned_data["action"] == forms.InvoiceEmailForm.ACTION_SEND:
# Send e-mails *ONLY* if we're sending.
send_mass_mail(emails)
messages.info(request, "The e-mails have been sent.")
data = {
"form": form,
"emails": emails,
}
return render(request, "registrasion/invoice_mailout.html", data) |
Renders a single user s badge ( SVG ). | def badge(request, user_id):
''' Renders a single user's badge (SVG). '''
user_id = int(user_id)
user = User.objects.get(pk=user_id)
rendered = render_badge(user)
response = HttpResponse(rendered)
response["Content-Type"] = "image/svg+xml"
response["Content-Disposition"] = 'inline; filename="badge.svg"'
return response |
Either displays a form containing a list of users with badges to render or returns a. zip file containing their badges. | def badges(request):
''' Either displays a form containing a list of users with badges to
render, or returns a .zip file containing their badges. '''
category = request.GET.getlist("category", [])
product = request.GET.getlist("product", [])
status = request.GET.get("status")
form = forms.InvoicesWithProductAndStatusForm(
request.POST or None,
category=category,
product=product,
status=status,
)
if form.is_valid():
response = HttpResponse()
response["Content-Type"] = "application.zip"
response["Content-Disposition"] = 'attachment; filename="badges.zip"'
z = zipfile.ZipFile(response, "w")
for invoice in form.cleaned_data["invoice"]:
user = invoice.user
badge = render_badge(user)
z.writestr("badge_%d.svg" % user.id, badge.encode("utf-8"))
return response
data = {
"form": form,
}
return render(request, "registrasion/badges.html", data) |
Renders a single user s badge. | def render_badge(user):
''' Renders a single user's badge. '''
data = {
"user": user,
}
t = loader.get_template('registrasion/badge.svg')
return t.render(data) |
Returns all discounts available to this user for the given categories and products. The discounts also list the available quantity for this user not including products that are pending purchase. | def available_discounts(cls, user, categories, products):
''' Returns all discounts available to this user for the given
categories and products. The discounts also list the available quantity
for this user, not including products that are pending purchase. '''
filtered_clauses = cls._filtered_clauses(user)
# clauses that match provided categories
categories = set(categories)
# clauses that match provided products
products = set(products)
# clauses that match categories for provided products
product_categories = set(product.category for product in products)
# (Not relevant: clauses that match products in provided categories)
all_categories = categories | product_categories
filtered_clauses = (
clause for clause in filtered_clauses
if hasattr(clause, 'product') and clause.product in products or
hasattr(clause, 'category') and clause.category in all_categories
)
discounts = []
# Markers so that we don't need to evaluate given conditions
# more than once
accepted_discounts = set()
failed_discounts = set()
for clause in filtered_clauses:
discount = clause.discount
cond = ConditionController.for_condition(discount)
past_use_count = clause.past_use_count
if past_use_count >= clause.quantity:
# This clause has exceeded its use count
pass
elif discount not in failed_discounts:
# This clause is still available
is_accepted = discount in accepted_discounts
if is_accepted or cond.is_met(user, filtered=True):
# This clause is valid for this user
discounts.append(DiscountAndQuantity(
discount=discount,
clause=clause,
quantity=clause.quantity - past_use_count,
))
accepted_discounts.add(discount)
else:
# This clause is not valid for this user
failed_discounts.add(discount)
return discounts |
Annotates the queryset with a usage count for that discount claus by the given user. | def _annotate_with_past_uses(cls, queryset, user):
''' Annotates the queryset with a usage count for that discount claus
by the given user. '''
if queryset.model == conditions.DiscountForCategory:
matches = (
Q(category=F('discount__discountitem__product__category'))
)
elif queryset.model == conditions.DiscountForProduct:
matches = (
Q(product=F('discount__discountitem__product'))
)
in_carts = (
Q(discount__discountitem__cart__user=user) &
Q(discount__discountitem__cart__status=commerce.Cart.STATUS_PAID)
)
past_use_quantity = When(
in_carts & matches,
then="discount__discountitem__quantity",
)
past_use_quantity_or_zero = Case(
past_use_quantity,
default=Value(0),
)
queryset = queryset.annotate(
past_use_count=Sum(past_use_quantity_or_zero)
)
return queryset |
Returns a list of all of the products that are available per flag conditions from the given categories. | def available_products(cls, user, category=None, products=None):
''' Returns a list of all of the products that are available per
flag conditions from the given categories. '''
if category is None and products is None:
raise ValueError("You must provide products or a category")
if category is not None:
all_products = inventory.Product.objects.filter(category=category)
all_products = all_products.select_related("category")
else:
all_products = []
if products is not None:
all_products = set(itertools.chain(all_products, products))
category_remainders = CategoryController.user_remainders(user)
product_remainders = ProductController.user_remainders(user)
passed_limits = set(
product
for product in all_products
if category_remainders[product.category.id] > 0
if product_remainders[product.id] > 0
)
failed_and_messages = FlagController.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)
return out |
Generates a credit note of the specified value and pays it against the given invoice. You need to call InvoiceController. update_status () to set the status correctly if appropriate. | def generate_from_invoice(cls, invoice, value):
''' Generates a credit note of the specified value and pays it against
the given invoice. You need to call InvoiceController.update_status()
to set the status correctly, if appropriate. '''
credit_note = commerce.CreditNote.objects.create(
invoice=invoice,
amount=0-value, # Credit notes start off as a payment against inv.
reference="ONE MOMENT",
)
credit_note.reference = "Generated credit note %d" % credit_note.id
credit_note.save()
return cls(credit_note) |
Applies the total value of this credit note to the specified invoice. If this credit note overpays the invoice a new credit note containing the residual value will be created. | def apply_to_invoice(self, invoice):
''' Applies the total value of this credit note to the specified
invoice. If this credit note overpays the invoice, a new credit note
containing the residual value will be created.
Raises ValidationError if the given invoice is not allowed to be
paid.
'''
# Local import to fix import cycles. Can we do better?
from .invoice import InvoiceController
inv = InvoiceController(invoice)
inv.validate_allowed_to_pay()
# Apply payment to invoice
commerce.CreditNoteApplication.objects.create(
parent=self.credit_note,
invoice=invoice,
amount=self.credit_note.value,
reference="Applied credit note #%d" % self.credit_note.id,
)
inv.update_status() |
Generates an invoice with a cancellation fee and applies credit to the invoice. | def cancellation_fee(self, percentage):
''' Generates an invoice with a cancellation fee, and applies
credit to the invoice.
percentage (Decimal): The percentage of the credit note to turn into
a cancellation fee. Must be 0 <= percentage <= 100.
'''
# Local import to fix import cycles. Can we do better?
from .invoice import InvoiceController
assert(percentage >= 0 and percentage <= 100)
cancellation_fee = self.credit_note.value * percentage / 100
due = datetime.timedelta(days=1)
item = [("Cancellation fee", cancellation_fee)]
invoice = InvoiceController.manual_invoice(
self.credit_note.invoice.user, due, item
)
if not invoice.is_paid:
self.apply_to_invoice(invoice)
return InvoiceController(invoice) |
Generates an access code for users payments as well as their fulfilment code for check - in. The access code will 4 characters long which allows for 1 500 625 unique codes which really should be enough for anyone. | def generate_access_code():
''' Generates an access code for users' payments as well as their
fulfilment code for check-in.
The access code will 4 characters long, which allows for 1,500,625
unique codes, which really should be enough for anyone. '''
length = 6
# all upper-case letters + digits 1-9 (no 0 vs O confusion)
chars = string.uppercase + string.digits[1:]
# 6 chars => 35 ** 6 = 1838265625 (should be enough for anyone)
return get_random_string(length=length, allowed_chars=chars) |
Produces a callable so that functions can be lazily evaluated in templates. | def lazy(function, *args, **kwargs):
''' Produces a callable so that functions can be lazily evaluated in
templates.
Arguments:
function (callable): The function to call at evaluation time.
args: Positional arguments, passed directly to ``function``.
kwargs: Keyword arguments, passed directly to ``function``.
Return:
callable: A callable that will evaluate a call to ``function`` with
the specified arguments.
'''
NOT_EVALUATED = object()
retval = [NOT_EVALUATED]
def evaluate():
if retval[0] is NOT_EVALUATED:
retval[0] = function(*args, **kwargs)
return retval[0]
return evaluate |
Returns the named object. | def get_object_from_name(name):
''' Returns the named object.
Arguments:
name (str): A string of form `package.subpackage.etc.module.property`.
This function will import `package.subpackage.etc.module` and
return `property` from that module.
'''
dot = name.rindex(".")
mod_name, property_name = name[:dot], name[dot + 1:]
__import__(mod_name)
return getattr(sys.modules[mod_name], property_name) |
Returns an invoice object for a given cart at its current revision. If such an invoice does not exist the cart is validated and if valid an invoice is generated. | def for_cart(cls, cart):
''' Returns an invoice object for a given cart at its current revision.
If such an invoice does not exist, the cart is validated, and if valid,
an invoice is generated.'''
cart.refresh_from_db()
try:
invoice = commerce.Invoice.objects.exclude(
status=commerce.Invoice.STATUS_VOID,
).get(
cart=cart,
cart_revision=cart.revision,
)
except ObjectDoesNotExist:
cart_controller = CartController(cart)
cart_controller.validate_cart() # Raises ValidationError on fail.
cls.update_old_invoices(cart)
invoice = cls._generate_from_cart(cart)
return cls(invoice) |
Generates an invoice for arbitrary items not held in a user s cart. | def manual_invoice(cls, user, due_delta, description_price_pairs):
''' Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice is
due.
description_price_pairs ([(str, long or Decimal), ...]): A list of
pairs. Each pair consists of the description for each line item
and the price for that line item. The price will be cast to
Decimal.
Returns:
an Invoice.
'''
line_items = []
for description, price in description_price_pairs:
line_item = commerce.LineItem(
description=description,
quantity=1,
price=Decimal(price),
product=None,
)
line_items.append(line_item)
min_due_time = timezone.now() + due_delta
return cls._generate(user, None, min_due_time, line_items) |
Generates an invoice for the given cart. | def _generate_from_cart(cls, cart):
''' Generates an invoice for the given cart. '''
cart.refresh_from_db()
# Generate the line items from the cart.
product_items = commerce.ProductItem.objects.filter(cart=cart)
product_items = product_items.select_related(
"product",
"product__category",
)
product_items = product_items.order_by(
"product__category__order", "product__order"
)
if len(product_items) == 0:
raise ValidationError("Your cart is empty.")
discount_items = commerce.DiscountItem.objects.filter(cart=cart)
discount_items = discount_items.select_related(
"discount",
"product",
"product__category",
)
def format_product(product):
return "%s - %s" % (product.category.name, product.name)
def format_discount(discount, product):
description = discount.description
return "%s (%s)" % (description, format_product(product))
line_items = []
for item in product_items:
product = item.product
line_item = commerce.LineItem(
description=format_product(product),
quantity=item.quantity,
price=product.price,
product=product,
)
line_items.append(line_item)
for item in discount_items:
line_item = commerce.LineItem(
description=format_discount(item.discount, item.product),
quantity=item.quantity,
price=cls.resolve_discount_value(item) * -1,
product=item.product,
)
line_items.append(line_item)
# Generate the invoice
min_due_time = cart.reservation_duration + cart.time_last_updated
return cls._generate(cart.user, cart, min_due_time, line_items) |
Applies the user s credit notes to the given invoice on creation. | def _apply_credit_notes(cls, invoice):
''' Applies the user's credit notes to the given invoice on creation.
'''
# We only automatically apply credit notes if this is the *only*
# unpaid invoice for this user.
invoices = commerce.Invoice.objects.filter(
user=invoice.user,
status=commerce.Invoice.STATUS_UNPAID,
)
if invoices.count() > 1:
return
notes = commerce.CreditNote.unclaimed().filter(
invoice__user=invoice.user
)
for note in notes:
try:
CreditNoteController(note).apply_to_invoice(invoice)
except ValidationError:
# ValidationError will get raised once we're overpaying.
break
invoice.refresh_from_db() |
Returns true if the accessing user is allowed to view this invoice or if the given access code matches this invoice s user s access code. | def can_view(self, user=None, access_code=None):
''' Returns true if the accessing user is allowed to view this invoice,
or if the given access code matches this invoice's user's access code.
'''
if user == self.invoice.user:
return True
if user.is_staff:
return True
if self.invoice.user.attendee.access_code == access_code:
return True
return False |
Refreshes the underlying invoice and cart objects. | def _refresh(self):
''' Refreshes the underlying invoice and cart objects. '''
self.invoice.refresh_from_db()
if self.invoice.cart:
self.invoice.cart.refresh_from_db() |
Passes cleanly if we re allowed to pay otherwise raise a ValidationError. | def validate_allowed_to_pay(self):
''' Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. '''
self._refresh()
if not self.invoice.is_unpaid:
raise ValidationError("You can only pay for unpaid invoices.")
if not self.invoice.cart:
return
if not self._invoice_matches_cart():
raise ValidationError("The registration has been amended since "
"generating this invoice.")
CartController(self.invoice.cart).validate_cart() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.