Search is not available for this dataset
text
stringlengths
75
104k
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. ''' ...
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 ) ...
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 pai...
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. quer...
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__presentati...
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())
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(f...
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 ObjectDoesNotE...
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 g...
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``. ...
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 amou...
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 = co...
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():...
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()) ...
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 vouche...
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. ...
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(discoun...
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....
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) ]
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 ...
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 r...
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...
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=lambd...
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") ...
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 = ["Cat...
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, )
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_not...
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__ca...
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( ...
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_...
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__prod...
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 QuerysetRepor...
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", "Va...
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 a...
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"...
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", } o...
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...
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__categor...
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 p...
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_conte...
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))
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 ...
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....
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 ...
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....
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...
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 ...
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 =...
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.P...
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 (vou...
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 unavailabl...
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 ...
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 invoic...
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 ``r...
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: ...
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): T...
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_r...
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_REFER...
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, ...
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; filena...
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.Invo...
def render_badge(user): ''' Renders a single user's badge. ''' data = { "user": user, } t = loader.get_template('registrasion/badge.svg') return t.render(data)
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._f...
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'))...
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") ...
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(...
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 ...
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 fi...
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...
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, pa...
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(".") ...
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...
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 i...
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( "produc...
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....
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: ...
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()
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: ...
def update_status(self): ''' Updates the status of this invoice based upon the total payments.''' old_status = self.invoice.status total_paid = self.invoice.total_payments() num_payments = commerce.PaymentBase.objects.filter( invoice=self.invoice, ).count() ...
def _mark_paid(self): ''' Marks the invoice as paid, and updates the attached cart if necessary. ''' cart = self.invoice.cart if cart: cart.status = commerce.Cart.STATUS_PAID cart.save() self.invoice.status = commerce.Invoice.STATUS_PAID self.invoi...
def _mark_refunded(self): ''' Marks the invoice as refunded, and updates the attached cart if necessary. ''' self._release_cart() self.invoice.status = commerce.Invoice.STATUS_REFUNDED self.invoice.save()
def _mark_void(self): ''' Marks the invoice as refunded, and updates the attached cart if necessary. ''' self.invoice.status = commerce.Invoice.STATUS_VOID self.invoice.save()
def _invoice_matches_cart(self): ''' Returns true if there is no cart, or if the revision of this invoice matches the current revision of the cart. ''' self._refresh() cart = self.invoice.cart if not cart: return True return cart.revision == self.invoice.ca...
def update_validity(self): ''' Voids this invoice if the attached cart is no longer valid because the cart revision has changed, or the reservations have expired. ''' is_valid = self._invoice_matches_cart() cart = self.invoice.cart if self.invoice.is_unpaid and is_valid and cart...
def void(self): ''' Voids the invoice if it is valid to do so. ''' if self.invoice.total_payments() > 0: raise ValidationError("Invoices with payments must be refunded.") elif self.invoice.is_refunded: raise ValidationError("Refunded invoices may not be voided.") ...
def refund(self): ''' Refunds the invoice by generating a CreditNote for the value of all of the payments against the cart. The invoice is marked as refunded, and the underlying cart is marked as released. ''' if self.invoice.is_void: raise ValidationError(...
def email(cls, invoice, kind): ''' Sends out an e-mail notifying the user about something to do with that invoice. ''' context = { "invoice": invoice, } send_email([invoice.user.email], kind, context=context)
def email_on_invoice_change(cls, invoice, old_status, new_status): ''' Sends out all of the necessary notifications that the status of the invoice has changed to: - Invoice is now paid - Invoice is now refunded ''' # The statuses that we don't care about. silen...
def update(self, data): """Update the object with new data.""" fields = [ 'id', 'status', 'type', 'persistence', 'date_start', 'date_finish', 'date_created', 'date_modified', 'checksum', ...
def _flatten_field(self, field, schema, path): """Reduce dicts of dicts to dot separated keys.""" flat = {} for field_schema, fields, path in iterate_schema(field, schema, path): name = field_schema['name'] typ = field_schema['type'] label = field_schema['labe...
def print_annotation(self): """Print annotation "key: value" pairs to standard output.""" for path, ann in self.annotation.items(): print("{}: {}".format(path, ann['value']))
def print_downloads(self): """Print file fields to standard output.""" for path, ann in self.annotation.items(): if path.startswith('output') and ann['type'] == 'basic:file:': print("{}: {}".format(path, ann['value']['file']))
def download(self, field): """Download a file. :param field: file field to download :type field: string :rtype: a file handle """ if not field.startswith('output'): raise ValueError("Only processor results (output.* fields) can be downloaded") if fi...
def add_arguments(cls, parser): """Add arguments to the parser for collection in app.args. Args: parser: `argparse.ArgumentParser`. Parser. Arguments added here are server on self.args. """ parser.add_argument( '-t...
def projects(self): """Return a list :obj:`GenProject` projects. :rtype: list of :obj:`GenProject` projects """ if not ('projects' in self.cache and self.cache['projects']): self.cache['projects'] = {c['id']: GenProject(c, self) for c in self.api.case.get()['objects']} ...
def project_data(self, project): """Return a list of Data objects for given project. :param project: ObjectId or slug of Genesis project :type project: string :rtype: list of Data objects """ projobjects = self.cache['project_objects'] objects = self.cache['obje...
def data(self, **query): """Query for Data object annotation.""" objects = self.cache['objects'] data = self.api.data.get(**query)['objects'] data_objects = [] for d in data: _id = d['id'] if _id in objects: # Update existing object ...
def processors(self, processor_name=None): """Return a list of Processor objects. :param project_id: ObjectId of Genesis project :type project_id: string :rtype: list of Processor objects """ if processor_name: return self.api.processor.get(name=processor_na...
def print_processor_inputs(self, processor_name): """Print processor input fields and types. :param processor_name: Processor object name :type processor_name: string """ p = self.processors(processor_name=processor_name) if len(p) == 1: p = p[0] el...
def rundata(self, strjson): """POST JSON data object to server""" d = json.loads(strjson) return self.api.data.post(d)