Changeset - 6dbc303e7c38
[Not reviewed]
0 3 0
Christopher Neugebauer - 8 years ago 2016-10-06 19:44:06
chrisjrn@gmail.com
Adds ability for staff to extend a user’s reservations
3 files changed with 25 insertions and 0 deletions:
0 comments (0 inline, 0 general)
registrasion/reporting/views.py
Show inline comments
 
import forms
 

	
 
import collections
 
import datetime
 
import itertools
 

	
 
from django.conf import settings
 
from django.contrib.auth.decorators import user_passes_test
 
from django.contrib.auth.models import User
 
from django.core.urlresolvers import reverse
 
from django.db import models
 
from django.db.models import F, Q
 
from django.db.models import Count, Max, Sum
 
from django.db.models import Case, When, Value
 
from django.db.models.fields.related import RelatedField
 
from django.shortcuts import render
 

	
 
from registrasion.controllers.cart import CartController
 
from registrasion.controllers.item import ItemController
 
from registrasion.models import commerce
 
from registrasion.models import people
 
from registrasion import util
 
from registrasion import views
 

	
 
from symposion.schedule import models as schedule_models
 

	
 
from reports import get_all_reports
 
from reports import Links
 
from reports import ListReport
 
from reports import QuerysetReport
 
from reports import report_view
 

	
 

	
 
def CURRENCY():
 
    return models.DecimalField(decimal_places=2)
 

	
 

	
 
AttendeeProfile = util.get_object_from_name(settings.ATTENDEE_PROFILE_MODEL)
 

	
 

	
 
@user_passes_test(views._staff_only)
 
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)
 

	
 

	
 
# Report functions
 

	
 
@report_view("Reconcilitation")
 
def reconciliation(request, form):
 
    ''' Shows the summary of sales, and the full history of payments and
 
    refunds into the system. '''
 

	
 
    return [
 
        sales_payment_summary(),
 
        items_sold(),
 
        payments(),
 
        credit_note_refunds(),
 
    ]
 

	
 

	
 
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"),
 
    )
 

	
 
    print line_items
 

	
 
    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)
 

	
 

	
 
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)
 

	
 

	
 
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_note,
 
    )
 

	
 

	
 
def group_by_cart_status(queryset, order, values):
 
    queryset = queryset.annotate(
 
        is_reserved=Case(
 
            When(cart__in=commerce.Cart.reserved_carts(), then=Value(True)),
 
            default=Value(False),
 
            output_field=models.BooleanField(),
 
        ),
 
    )
 

	
 
    values = queryset.order_by(*order).values(*values)
 
    values = values.annotate(
 
        total_paid=Sum(Case(
 
            When(
 
                cart__status=commerce.Cart.STATUS_PAID,
 
                then=F("quantity"),
 
            ),
...
 
@@ -228,391 +229,400 @@ def group_by_cart_status(queryset, order, values):
 
        )),
 
        total_reserved=Sum(Case(
 
            When(
 
                (
 
                    Q(cart__status=commerce.Cart.STATUS_ACTIVE) &
 
                    Q(is_reserved=True)
 
                ),
 
                then=F("quantity"),
 
            ),
 
            default=Value(0),
 
        )),
 
    )
 

	
 
    return values
 

	
 

	
 
@report_view("Product status", form_type=forms.ProductAndCategoryForm)
 
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)
 

	
 

	
 
@report_view("Product status", form_type=forms.DiscountForm)
 
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)
 

	
 

	
 
@report_view("Paid invoices by date", form_type=forms.ProductAndCategoryForm)
 
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,
 
    )
 

	
 
@report_view("Credit notes")
 
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"],  # NOQA
 
        notes,
 
        headings=["id", "Owner", "Status", "Value"],
 
        link_view=views.credit_note,
 
    )
 

	
 

	
 
class AttendeeListReport(ListReport):
 

	
 
    def get_link(self, argument):
 
        return reverse(self._link_view) + "?user=%d" % int(argument)
 

	
 

	
 
@report_view("Attendee", form_type=forms.UserIdForm)
 
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 not form.has_changed():
 
        return attendee_list(request)
 

	
 
    if form.cleaned_data["user"] is not None:
 
        user_id = form.cleaned_data["user"]
 

	
 
    attendee = people.Attendee.objects.get(user__id=user_id)
 
    name = attendee.attendeeprofilebase.attendee_name()
 

	
 
    reports = []
 

	
 
    profile_data = []
 
    profile = people.AttendeeProfileBase.objects.get_subclass(
 
        attendee=attendee
 
    )
 
    exclude = set(["attendeeprofilebase_ptr", "id"])
 
    for field in profile._meta.get_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)
 
        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.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
 

	
 

	
 
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)
 

	
 

	
 
ProfileForm = forms.model_fields_form_factory(AttendeeProfile)
 

	
 
@report_view(
 
    "Attendees By Product/Category",
 
    form_type=forms.mix_form(
 
        forms.ProductAndCategoryForm, ProfileForm, forms.GroupByForm
 
    ),
 
)
 
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")
 

	
 
    # 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"
 
    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], )
 
    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])
 

	
 
    # 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(
 
                attendee__user__cart__status=status,
 
                then=Value(1),
 
            ),
registrasion/urls.py
Show inline comments
 
from reporting import views as rv
 

	
 
from django.conf.urls import include
 
from django.conf.urls import url
 

	
 
from .views import (
 
    amend_registration,
 
    checkout,
 
    credit_note,
 
    edit_profile,
 
    extend_reservation,
 
    guided_registration,
 
    invoice,
 
    invoice_access,
 
    manual_payment,
 
    product_category,
 
    refund,
 
    review,
 
)
 

	
 

	
 
public = [
 
    url(r"^amend/([0-9]+)$", amend_registration, name="amend_registration"),
 
    url(r"^category/([0-9]+)$", product_category, name="product_category"),
 
    url(r"^checkout$", checkout, name="checkout"),
 
    url(r"^checkout/([0-9]+)$", checkout, name="checkout"),
 
    url(r"^credit_note/([0-9]+)$", credit_note, name="credit_note"),
 
    url(r"^extend/([0-9]+)$", extend_reservation, name="extend_reservation"),
 
    url(r"^invoice/([0-9]+)$", invoice, name="invoice"),
 
    url(r"^invoice/([0-9]+)/([A-Z0-9]+)$", invoice, name="invoice"),
 
    url(r"^invoice/([0-9]+)/manual_payment$",
 
        manual_payment, name="manual_payment"),
 
    url(r"^invoice/([0-9]+)/refund$",
 
        refund, name="refund"),
 
    url(r"^invoice_access/([A-Z0-9]+)$", invoice_access,
 
        name="invoice_access"),
 
    url(r"^profile$", edit_profile, name="attendee_edit"),
 
    url(r"^register$", guided_registration, name="guided_registration"),
 
    url(r"^review$", review, name="review"),
 
    url(r"^register/([0-9]+)$", guided_registration,
 
        name="guided_registration"),
 
]
 

	
 

	
 
reports = [
 
    url(r"^$", rv.reports_list, name="reports_list"),
 
    url(r"^attendee/?$", rv.attendee, name="attendee"),
 
    url(r"^attendee_data/?$", rv.attendee_data, name="attendee_data"),
 
    url(r"^attendee/([0-9]*)$", rv.attendee, name="attendee"),
 
    url(r"^credit_notes/?$", rv.credit_notes, name="credit_notes"),
 
    url(r"^discount_status/?$", rv.discount_status, name="discount_status"),
 
    url(
 
        r"^paid_invoices_by_date/?$",
 
        rv.paid_invoices_by_date,
 
        name="paid_invoices_by_date"
 
    ),
 
    url(r"^product_status/?$", rv.product_status, name="product_status"),
 
    url(r"^reconciliation/?$", rv.reconciliation, name="reconciliation"),
 
    url(
 
        r"^speaker_registrations/?$",
 
        rv.speaker_registrations,
 
        name="speaker_registrations",
 
    ),
 
]
 

	
 

	
 
urlpatterns = [
 
    url(r"^reports/", include(reports)),
 
    url(r"^", include(public))  # This one must go last.
 
]
registrasion/views.py
Show inline comments
 
import datetime
 
import sys
 
import util
 

	
 
from registrasion import forms
 
from registrasion import util
 
from registrasion.models import commerce
 
from registrasion.models import inventory
 
from registrasion.models import people
 
from registrasion.controllers.batch import BatchController
 
from registrasion.controllers.cart import CartController
 
from registrasion.controllers.credit_note import CreditNoteController
 
from registrasion.controllers.discount import DiscountController
 
from registrasion.controllers.invoice import InvoiceController
 
from registrasion.controllers.item import ItemController
 
from registrasion.controllers.product import ProductController
 
from registrasion.exceptions import CartValidationError
 

	
 
from collections import namedtuple
 

	
 
from django import forms as django_forms
 
from django.conf import settings
 
from django.contrib.auth.decorators import login_required
 
from django.contrib.auth.decorators import user_passes_test
 
from django.contrib.auth.models import User
 
from django.contrib import messages
 
from django.core.exceptions import ObjectDoesNotExist
 
from django.core.exceptions import ValidationError
 
from django.http import Http404
 
from django.shortcuts import redirect
 
from django.shortcuts import render
 

	
 

	
 
_GuidedRegistrationSection = namedtuple(
 
    "GuidedRegistrationSection",
 
    (
 
        "title",
 
        "discounts",
 
        "description",
 
        "form",
 
    )
 
)
 

	
 

	
 
@util.all_arguments_optional
 
class GuidedRegistrationSection(_GuidedRegistrationSection):
 
    ''' Represents a section of a guided registration page.
 

	
 
    Attributes:
 
       title (str): The title of the section.
 

	
 
       discounts ([registrasion.contollers.discount.DiscountAndQuantity, ...]):
 
            A list of discount objects that are available in the section. You
 
            can display ``.clause`` to show what the discount applies to, and
 
            ``.quantity`` to display the number of times that discount can be
 
            applied.
 

	
 
       description (str): A description of the section.
 

	
 
       form (forms.Form): A form to display.
 
    '''
 
    pass
 

	
 

	
 
@login_required
 
def guided_registration(request):
 
    ''' Goes through the registration process in order, making sure user sees
 
    all valid categories.
 

	
 
    The user must be logged in to see this view.
 

	
 
    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
 
                }
 

	
 
    '''
 

	
 
    SESSION_KEY = "guided_registration_categories"
 
    ASK_FOR_PROFILE = 777  # Magic number. Meh.
 

	
 
    next_step = redirect("guided_registration")
 

	
 
    sections = []
 

	
 
    attendee = people.Attendee.get_instance(request.user)
 

	
 
    if attendee.completed_registration:
 
        return redirect(review)
 

	
 
    # Step 1: Fill in a badge and collect a voucher code
 
    try:
 
        profile = attendee.attendeeprofilebase
 
    except ObjectDoesNotExist:
 
        profile = None
 

	
 
    # Figure out if we need to show the profile form and the voucher form
 
    show_profile_and_voucher = False
 
    if SESSION_KEY not in request.session:
 
        if not profile:
 
            show_profile_and_voucher = True
 
    else:
 
        if request.session[SESSION_KEY] == ASK_FOR_PROFILE:
 
            show_profile_and_voucher = True
 

	
 
    if show_profile_and_voucher:
 
        # Keep asking for the profile until everything passes.
 
        request.session[SESSION_KEY] = ASK_FOR_PROFILE
 

	
 
        voucher_form, voucher_handled = _handle_voucher(request, "voucher")
 
        profile_form, profile_handled = _handle_profile(request, "profile")
 

	
 
        voucher_section = GuidedRegistrationSection(
 
            title="Voucher Code",
 
            form=voucher_form,
 
        )
 

	
 
        profile_section = GuidedRegistrationSection(
 
            title="Profile and Personal Information",
 
            form=profile_form,
 
        )
 

	
 
        title = "Attendee information"
 
        current_step = 1
 
        sections.append(voucher_section)
 
        sections.append(profile_section)
 
    else:
 
        # We're selling products
 

	
 
        starting = attendee.guided_categories_complete.count() == 0
 

	
 
        # Get the next category
 
        cats = inventory.Category.objects
 
        if SESSION_KEY in request.session:
 
            _cats = request.session[SESSION_KEY]
 
            cats = cats.filter(id__in=_cats)
 
        else:
 
            cats = cats.exclude(
 
                id__in=attendee.guided_categories_complete.all(),
 
            )
 

	
 
        cats = cats.order_by("order")
 

	
 
        request.session[SESSION_KEY] = []
 

	
 
        if starting:
 
            # Only display the first Category
 
            title = "Select ticket type"
 
            current_step = 2
 
            cats = [cats[0]]
 
        else:
 
            # Set title appropriately for remaining categories
 
            current_step = 3
 
            title = "Additional items"
 

	
 
        all_products = inventory.Product.objects.filter(
 
            category__in=cats,
 
        ).select_related("category")
 

	
 
        with BatchController.batch(request.user):
 
            available_products = set(ProductController.available_products(
 
                request.user,
 
                products=all_products,
 
            ))
 

	
 
            if len(available_products) == 0:
 
                # We've filled in every category
 
                attendee.completed_registration = True
 
                attendee.save()
 
                return next_step
 

	
 
            for category in cats:
 
                products = [
 
                    i for i in available_products
 
                    if i.category == category
 
                ]
 

	
 
                prefix = "category_" + str(category.id)
 
                p = _handle_products(request, category, products, prefix)
 
                products_form, discounts, products_handled = p
 

	
 
                section = GuidedRegistrationSection(
 
                    title=category.name,
 
                    description=category.description,
 
                    discounts=discounts,
...
 
@@ -714,192 +715,204 @@ def manual_payment(request, invoice_id):
 
        "form": form,
 
    }
 

	
 
    return render(request, "registrasion/manual_payment.html", data)
 

	
 

	
 
@user_passes_test(_staff_only)
 
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)
 

	
 

	
 
@user_passes_test(_staff_only)
 
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)
 

	
 

	
 
@user_passes_test(_staff_only)
 
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)
 

	
 

	
 
@user_passes_test(_staff_only)
 
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"])
0 comments (0 inline, 0 general)