예제 #1
0
def new_sale(request):
    post = json.loads(request.body)
    now = timezone.localtime(timezone.now())

    # sale
    sale = Sale()
    sale.event = get_current_event()
    sale.first_name = post['sale'].get('first_name', '')
    sale.last_name = post['sale'].get('last_name', '')
    sale.email = post['sale'].get('email', '')
    sale.payment_type = post['sale']['payment_type']
    if post['sale'].get('coupon_code', None):
        code = list(
            CouponCode.objects.filter(code=post['sale']['coupon_code']))
        if code:
            sale.coupon_code = code
    sale.amount = post['sale']['amount']

    if post['sale'].get('transaction_id', None):
        sale.transaction_id = post['sale']['transaction_id']

    sale.created = now
    sale.success = True
    sale.save()

    # ticket
    ticket = Ticket()
    ticket.event = get_current_event()
    ticket.sale = sale
    ticket.type_id = post['ticket']['type']
    ticket.first_name = post['ticket']['first_name']
    ticket.last_name = post['ticket']['last_name']
    ticket.email = post['ticket']['email']
    ticket.twitter = post['ticket']['twitter']
    ticket.organization = post['ticket']['organization']
    ticket.checked_in = now if post['ticket']['checked_in'] else None

    ticket.success = True
    ticket.save()

    if post['sale']['send_receipts']:
        send_sale_email(sale.id)

    return HttpResponse(json.dumps({
        'status':
        'OK',
        'url':
        '/register/badges/' + ticket.short_barcode + '.json?key=' +
        request.GET['key'],
        'barcode':
        ticket.short_barcode
    }),
                        content_type="application/json")
예제 #2
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def get_price_data(tickets={}, coupon=None):
    out = {}
    total = 0
    total_qty = 0
    for tk, qty in tickets.items():
        ticket = TicketType.objects.get(id=tk)
        total += float(ticket.price) * qty
        total_qty += qty

    if coupon:
        cpl = list(
            CouponCode.objects.filter(event=get_current_event(), code=coupon))
        if len(cpl):
            cp = cpl[0]
            too_many = False
            if cp.max_tickets != 0:
                so_far = Ticket.objects.filter(success=True,
                                               sale__coupon_code=cp).count()
                left = cp.max_tickets - so_far
                if total_qty > left:
                    too_many = True

            if too_many:
                out['coupon_error'] = "Not enough tickets are left for this coupon to cover your order."
            else:
                out['coupon'] = coupon
                total -= (cp.discount / 100.0) * total
        else:
            out['coupon_error'] = "Coupon code not found."
    out['price'] = total

    return out
예제 #3
0
def get_attendee_export():
    outfile = StringIO()
    outcsv = csv.DictWriter(outfile, [
        'ticket_id', 'first_name', 'last_name', 'organization', 'email',
        'ticket_type', 'ambassador', 'checked_in'
    ])
    outcsv.writeheader()
    ambassador_choices = dict(AMBASSADOR_PROGRAM_CHOICES)

    from sked.utils import get_current_event
    for ticket in Ticket.objects.filter(
            event=get_current_event(),
            sale__success=True).order_by('id').select_related():
        outcsv.writerow({
            'ticket_id':
            ticket.id,
            'first_name':
            ticket.first_name.encode('utf8'),
            'last_name':
            ticket.last_name.encode('utf8'),
            'organization':
            ticket.organization.encode('utf8'),
            'email':
            ticket.email,
            'ticket_type':
            ticket.type.name,
            'ambassador':
            ambassador_choices[ticket.ambassador_program],
            'checked_in':
            "Y" if ticket.checked_in else "N"
        })

    return outfile.getvalue()
예제 #4
0
    def handle(self, *args, **options):
        from sked.utils import get_current_event

        search = {'success': True, 'event': get_current_event()}

        query = Ticket.objects.filter(**search)

        fdomain = '@%s' % options['staff_domain'] if options[
            'staff_domain'] else None
        fcoupon = CouponCode.objects.get(
            code=options['staff_coupon']
        ) if options['staff_coupon'] else CouponCode()

        outs = cStringIO.StringIO()
        outc = csv.DictWriter(outs, [
            'first_name', 'last_name', 'email', 'address1', 'address2', 'city',
            'state', 'zip', 'organization', 'ticket_type', 'is_staff'
        ])
        outc.writeheader()

        for ticket in query.order_by('id').select_related():
            if ticket.lobby_day:
                staff = (ticket.email and fdomain and fdomain in ticket.email) or \
                    (ticket.sale.email and fdomain and fdomain in ticket.sale.email) or \
                    (ticket.sale.coupon_code and ticket.sale.coupon_code.id == fcoupon.id)

                if ticket.sale.state == 'non-us':
                    continue

                outc.writerow({
                    'first_name':
                    ticket.first_name.encode('utf8'),
                    'last_name':
                    ticket.last_name.encode('utf8'),
                    'email':
                    ticket.email.encode('utf8'),
                    'address1':
                    ticket.sale.address1.encode('utf8'),
                    'address2':
                    ticket.sale.address2.encode('utf8'),
                    'city':
                    ticket.sale.city.encode('utf8'),
                    'state':
                    ticket.sale.state.encode('utf8'),
                    'zip':
                    ticket.sale.zip.encode('utf8'),
                    'organization':
                    ticket.organization.encode('utf8'),
                    'ticket_type':
                    ticket.type.name,
                    'is_staff':
                    'Y' if staff else 'N',
                })

        if options['output']:
            f = open(options['output'], 'wb')
            f.write(outs.getvalue())
            f.close()
        else:
            print outs.getvalue()
예제 #5
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def get_price_data(tickets={}, coupon=None):
    out = {}
    total = 0
    total_qty = 0
    for tk, qty in tickets.items():
        ticket = TicketType.objects.get(id=tk)
        total += float(ticket.price) * qty
        total_qty += qty

    if coupon:
        cpl = list(CouponCode.objects.filter(event=get_current_event(), code=coupon))
        if len(cpl):
            cp = cpl[0]
            too_many = False
            if cp.max_tickets != 0:
                so_far = Ticket.objects.filter(success=True, sale__coupon_code=cp).count()
                left = cp.max_tickets - so_far
                if total_qty > left:
                    too_many = True

            if too_many:
                out["coupon_error"] = "Not enough tickets are left for this coupon to cover your order."
            else:
                out["coupon"] = coupon
                total -= (cp.discount / 100.0) * total
        else:
            out["coupon_error"] = "Coupon code not found."
    out["price"] = total

    return out
예제 #6
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def _open_register(request):
    payment_form = PaymentForm()
    ticket_form = TicketForm()

    ticket_types = TicketType.objects.filter(event=get_current_event(),
                                             enabled=True,
                                             online=True).order_by('position')

    return render_to_response(
        'reg/register.html', {
            'ticket_form': ticket_form,
            'payment_form': payment_form,
            'ticket_types': ticket_types,
            'BRAINTREE_CSE_KEY': getattr(settings, "BRAINTREE_CSE_KEY", ""),
            'event': get_current_event(),
            'registration_is_open': True
        },
        context_instance=RequestContext(request))
예제 #7
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def _open_register(request):
    payment_form = PaymentForm()
    ticket_form = TicketForm()

    ticket_types = TicketType.objects.filter(event=get_current_event(), enabled=True, online=True).order_by("position")

    return render_to_response(
        "reg/register.html",
        {
            "ticket_form": ticket_form,
            "payment_form": payment_form,
            "ticket_types": ticket_types,
            "BRAINTREE_CSE_KEY": getattr(settings, "BRAINTREE_CSE_KEY", ""),
            "event": get_current_event(),
            "registration_is_open": True,
        },
        context_instance=RequestContext(request),
    )
예제 #8
0
파일: reports.py 프로젝트: crdunwel/tcamp
def get_volunteer_export():
    outfile = StringIO()
    outcsv = csv.DictWriter(outfile, ['ticket_id', 'first_name', 'last_name', 'organization', 'email', 'checked_in'])
    outcsv.writeheader()

    from sked.utils import get_current_event
    for ticket in Ticket.objects.filter(event=get_current_event(), sale__success=True, type__name__contains="Volunteer").order_by('id').select_related():
        outcsv.writerow({'ticket_id': ticket.id, 'first_name': ticket.first_name, 'last_name': ticket.last_name, 'organization': ticket.organization, 'email': ticket.email, 'checked_in': "Y" if ticket.checked_in else "N"})

    return outfile.getvalue()
예제 #9
0
파일: badges.py 프로젝트: crdunwel/tcamp
def new_sale(request):
    post = json.loads(request.body)
    now = timezone.localtime(timezone.now())

    # sale
    sale = Sale()
    sale.event = get_current_event()
    sale.first_name = post['sale'].get('first_name', '')
    sale.last_name = post['sale'].get('last_name', '')
    sale.email = post['sale'].get('email', '')
    sale.payment_type = post['sale']['payment_type']
    if post['sale'].get('coupon_code', None):
        code = list(CouponCode.objects.filter(code=post['sale']['coupon_code']))
        if code:
            sale.coupon_code = code
    sale.amount = post['sale']['amount']

    if post['sale'].get('transaction_id', None):
        sale.transaction_id = post['sale']['transaction_id']

    sale.created = now
    sale.success = True
    sale.save()

    # ticket
    ticket = Ticket()
    ticket.event = get_current_event()
    ticket.sale = sale
    ticket.type_id = post['ticket']['type']
    ticket.first_name = post['ticket']['first_name']
    ticket.last_name = post['ticket']['last_name']
    ticket.email = post['ticket']['email']
    ticket.twitter = post['ticket']['twitter']
    ticket.organization = post['ticket']['organization']
    ticket.checked_in = now if post['ticket']['checked_in'] else None
    
    ticket.success = True
    ticket.save()

    if post['sale']['send_receipts']:
        send_sale_email(sale.id)

    return HttpResponse(json.dumps({'status': 'OK', 'url': '/register/badges/' + ticket.short_barcode + '.json?key=' + request.GET['key'], 'barcode': ticket.short_barcode}), content_type="application/json")
예제 #10
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def whos_going(request):
    attendees = Ticket.objects.filter(event=get_current_event(),
                                      success=True).order_by('-id')
    out = [{
        'first_name': a.first_name,
        'last_name': a.last_name,
        'organization': a.organization,
        'twitter': a.clean_twitter
    } for a in attendees]
    return HttpResponse(json.dumps({'attendees': out}),
                        content_type="application/json")
예제 #11
0
파일: reports.py 프로젝트: crdunwel/tcamp
def get_attendee_export():
    outfile = StringIO()
    outcsv = csv.DictWriter(outfile, ['ticket_id', 'first_name', 'last_name', 'organization', 'email', 'ticket_type', 'ambassador', 'checked_in'])
    outcsv.writeheader()
    ambassador_choices = dict(AMBASSADOR_PROGRAM_CHOICES)

    from sked.utils import get_current_event
    for ticket in Ticket.objects.filter(event=get_current_event(), sale__success=True).order_by('id').select_related():
        outcsv.writerow({'ticket_id': ticket.id, 'first_name': ticket.first_name.encode('utf8'), 'last_name': ticket.last_name.encode('utf8'), 'organization': ticket.organization.encode('utf8'), 'email': ticket.email, 'ticket_type': ticket.type.name, 'ambassador': ambassador_choices[ticket.ambassador_program], 'checked_in': "Y" if ticket.checked_in else "N"})

    return outfile.getvalue()
예제 #12
0
class CouponCodeAdmin(EnhancedModelAdminMixin, DefaultFilterMixin,
                      admin.ModelAdmin):
    list_display = ('code', 'event', 'discount_percentage', 'ticket_limit')
    list_filter = ('event', )
    default_filters = (('event__id__exact', lambda: get_current_event().id), )

    def discount_percentage(self, obj):
        return "%s%%" % int(obj.discount)

    def ticket_limit(self, obj):
        return "Unlimited" if obj.max_tickets == 0 else obj.max_tickets
예제 #13
0
def get_attendees(request, format):
    staff_domains = get_staff_domains()
    fdomains = ['@%s' % domain
                for domain in staff_domains] if staff_domains else []
    fcoupon = set([c.id for c in CouponCode.objects.filter(is_staff=True)])

    out = []
    prefix = '' if (
        format == 'zip' or not request
    ) else request.build_absolute_uri('/register/badges/qrcode/')
    compact = format != 'json'
    for ticket in Ticket.objects.filter(success=True,
                                        event=get_current_event()).order_by(
                                            'sale__created').select_related():
        out.append(get_badge(ticket, prefix, compact))

    if format == 'json':
        return HttpResponse(json.dumps({'attendees': out}),
                            content_type="application/json")
    elif format in ('csv', 'zip'):
        csvbuff = StringIO()
        outc = csv.DictWriter(csvbuff, [
            'first_name', 'last_name', 'registered', 'qrcode', 'qrcode_png',
            'qrcode_svg', 'email', 'twitter', 'organization', 'is_staff',
            'icon', 'checked_in', 'ambassador_program'
        ])
        outc.writeheader()

        for row in out:
            outc.writerow(
                dict([
                    (key,
                     value.encode('utf8') if type(value) == unicode else value)
                    for key, value in row.items()
                ]))

        if format == 'csv':
            return HttpResponse(csvbuff.getvalue(), content_type="text/csv")
        elif format == 'zip':
            zipbuff = StringIO()
            outz = zipfile.ZipFile(zipbuff, 'w', zipfile.ZIP_DEFLATED)

            outz.writestr('export.csv', csvbuff.getvalue())
            for row in out:
                img_data = get_qrcode_image(row['qrcode'], 'both')
                outz.writestr(row['qrcode_png'], img_data['png'],
                              zipfile.ZIP_STORED)
                outz.writestr(row['qrcode_svg'], img_data['svg'])

            outz.close()

            return HttpResponse(zipbuff.getvalue(),
                                content_type="application/zip")
예제 #14
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def whos_going(request):
    attendees = Ticket.objects.filter(event=get_current_event(), success=True).order_by("-id")
    out = [
        {
            "first_name": a.first_name,
            "last_name": a.last_name,
            "organization": a.organization,
            "twitter": a.clean_twitter,
        }
        for a in attendees
    ]
    return HttpResponse(json.dumps({"attendees": out}), content_type="application/json")
예제 #15
0
def get_registration_report():
    from sked.utils import get_current_event
    current_event = get_current_event()

    search = {'success': True, 'event': current_event}

    query = Ticket.objects.filter(**search)

    staff_domains = get_staff_domains()
    fdomains = ['@%s' % domain
                for domain in staff_domains] if staff_domains else []
    fcoupon = set([c.id for c in CouponCode.objects.filter(is_staff=True)])

    sales = {}
    stats = defaultdict(int)
    coupons = defaultdict(int)
    types = defaultdict(int)
    ambassador = defaultdict(int)
    type_labels = {}
    for ticket in query.order_by('id').select_related():
        sales[ticket.sale.id] = ticket.sale

        stats['tickets'] += 1
        if (ticket.email and any([fdomain in ticket.email for fdomain in fdomains])) or \
            (ticket.sale.coupon_code and ticket.sale.coupon_code.id in fcoupon):
            stats['staff'] += 1
        else:
            stats['non_staff'] += 1
            types[ticket.type.id] += 1
            type_labels[ticket.type.id] = ticket.type.name

        if ticket.sale.coupon_code and not ticket.sale.coupon_code.is_staff:
            stats['ns_coupon'] += 1
            coupons[ticket.sale.coupon_code.code] += 1

        if ticket.lobby_day:
            stats['lobby_day'] += 1

        ambassador[ticket.ambassador_program] += 1

    return {
        'stats':
        stats,
        'type_breakdown':
        [(type_labels[i], types[i]) for i in sorted(types.keys())],
        'ambassador_counts': [(label, ambassador[key])
                              for key, label in AMBASSADOR_PROGRAM_CHOICES],
        'total_sales':
        sum([float(sale.amount) for sale in sales.values()]),
        'coupons':
        dict(coupons)
    }
예제 #16
0
class SaleAdmin(EnhancedModelAdminMixin, DefaultFilterMixin, admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'email', 'event', 'success',
                    'coupon_code')
    list_filter = ('event', 'success', 'payment_type', 'coupon_code')
    default_filters = (('event__id__exact', lambda: get_current_event().id),
                       ('success__exact', 1))

    def coupon_code(self, obj):
        return obj.coupon_code.code if obj.coupon_code else ""

    def queryset(self, request):
        qs = super(SaleAdmin, self).queryset(request)
        return qs.select_related('coupon_code')
예제 #17
0
파일: reports.py 프로젝트: crdunwel/tcamp
def get_registration_report():
    from sked.utils import get_current_event
    current_event = get_current_event()

    search = {
        'success': True,
        'event': current_event
    }

    query = Ticket.objects.filter(**search)

    staff_domains = get_staff_domains()
    fdomains = ['@%s' % domain for domain in staff_domains] if staff_domains else []
    fcoupon = set([c.id for c in CouponCode.objects.filter(is_staff=True)])

    sales = {}
    stats = defaultdict(int)
    coupons = defaultdict(int)
    types = defaultdict(int)
    ambassador = defaultdict(int)
    type_labels = {}
    for ticket in query.order_by('id').select_related():
        sales[ticket.sale.id] = ticket.sale

        stats['tickets'] += 1
        if (ticket.email and any([fdomain in ticket.email for fdomain in fdomains])) or \
            (ticket.sale.coupon_code and ticket.sale.coupon_code.id in fcoupon):
                stats['staff'] += 1
        else:
            stats['non_staff'] += 1
            types[ticket.type.id] += 1
            type_labels[ticket.type.id] = ticket.type.name

        if ticket.sale.coupon_code and not ticket.sale.coupon_code.is_staff:
            stats['ns_coupon'] += 1
            coupons[ticket.sale.coupon_code.code] += 1

        if ticket.lobby_day:
            stats['lobby_day'] += 1

        ambassador[ticket.ambassador_program] += 1


    return {
        'stats': stats,
        'type_breakdown': [(type_labels[i], types[i]) for i in sorted(types.keys())],
        'ambassador_counts': [(label, ambassador[key]) for key, label in AMBASSADOR_PROGRAM_CHOICES],
        'total_sales': sum([float(sale.amount) for sale in sales.values()]),
        'coupons': dict(coupons)
    }
예제 #18
0
    def handle(self, *args, **options):
        from sked.utils import get_current_event

        search = {
            'success': True,
            'event': get_current_event()
        }

        query = Ticket.objects.filter(**search)

        fdomain = '@%s' % options['staff_domain'] if options['staff_domain'] else None
        fcoupon = CouponCode.objects.get(code=options['staff_coupon']) if options['staff_coupon'] else CouponCode()

        outs = cStringIO.StringIO()
        outc = csv.DictWriter(outs, ['first_name', 'last_name', 'email', 'address1', 'address2', 'city', 'state', 'zip', 'organization', 'ticket_type', 'is_staff'])
        outc.writeheader()

        for ticket in query.order_by('id').select_related():
            if ticket.lobby_day:
                staff = (ticket.email and fdomain and fdomain in ticket.email) or \
                    (ticket.sale.email and fdomain and fdomain in ticket.sale.email) or \
                    (ticket.sale.coupon_code and ticket.sale.coupon_code.id == fcoupon.id)

                if ticket.sale.state == 'non-us':
                    continue

                outc.writerow({
                    'first_name': ticket.first_name.encode('utf8'),
                    'last_name': ticket.last_name.encode('utf8'),
                    'email': ticket.email.encode('utf8'),
                    'address1': ticket.sale.address1.encode('utf8'),
                    'address2': ticket.sale.address2.encode('utf8'),
                    'city': ticket.sale.city.encode('utf8'),
                    'state': ticket.sale.state.encode('utf8'),
                    'zip': ticket.sale.zip.encode('utf8'),
                    'organization': ticket.organization.encode('utf8'),
                    'ticket_type': ticket.type.name,
                    'is_staff': 'Y' if staff else 'N',
                })

        if options['output']:
            f = open(options['output'], 'wb')
            f.write(outs.getvalue())
            f.close()
        else:
            print outs.getvalue()
예제 #19
0
class TicketAdmin(EnhancedModelAdminMixin, DefaultFilterMixin,
                  admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'email', 'event', 'type',
                    'success', 'payment_type', 'coupon_code')
    list_filter = ('event', 'type', 'success', 'sale__payment_type',
                   'sale__coupon_code')
    exclude = ('checked_in', )
    default_filters = (('event__id__exact', lambda: get_current_event().id),
                       ('success__exact', 1))
    actions = [export_as_csv_action]

    def payment_type(self, obj):
        return dict(PAYMENT_TYPE_CHOICES)[obj.sale.payment_type]

    def coupon_code(self, obj):
        return obj.sale.coupon_code

    def queryset(self, request):
        qs = super(TicketAdmin, self).queryset(request)
        return qs.select_related('sale', 'sale__coupon_code')
예제 #20
0
파일: badges.py 프로젝트: crdunwel/tcamp
def get_attendees(request, format):
    staff_domains = get_staff_domains()
    fdomains = ['@%s' % domain for domain in staff_domains] if staff_domains else []
    fcoupon = set([c.id for c in CouponCode.objects.filter(is_staff=True)])

    out = []
    prefix = '' if (format == 'zip' or not request) else request.build_absolute_uri('/register/badges/qrcode/')
    compact = format != 'json'
    for ticket in Ticket.objects.filter(success=True, event=get_current_event()).order_by('sale__created').select_related():
        out.append(get_badge(ticket, prefix, compact))

    if format == 'json':
        return HttpResponse(json.dumps({'attendees': out}), content_type="application/json")
    elif format in ('csv', 'zip'):
        csvbuff = StringIO()        
        outc = csv.DictWriter(csvbuff, ['first_name', 'last_name', 'registered', 'qrcode', 'qrcode_png', 'qrcode_svg', 'email', 'twitter', 'organization', 'is_staff', 'icon', 'checked_in', 'ambassador_program'])
        outc.writeheader()
        
        for row in out:
            outc.writerow(
                dict([(key, value.encode('utf8') if type(value) == unicode else value) for key, value in row.items()])
            )

        if format == 'csv':
            return HttpResponse(csvbuff.getvalue(), content_type="text/csv")
        elif format == 'zip':
            zipbuff = StringIO()
            outz = zipfile.ZipFile(zipbuff, 'w', zipfile.ZIP_DEFLATED)

            outz.writestr('export.csv', csvbuff.getvalue())
            for row in out:
                img_data = get_qrcode_image(row['qrcode'], 'both')
                outz.writestr(row['qrcode_png'], img_data['png'], zipfile.ZIP_STORED)
                outz.writestr(row['qrcode_svg'], img_data['svg'])

            outz.close()

            return HttpResponse(zipbuff.getvalue(), content_type="application/zip")
예제 #21
0
def get_volunteer_export():
    outfile = StringIO()
    outcsv = csv.DictWriter(outfile, [
        'ticket_id', 'first_name', 'last_name', 'organization', 'email',
        'checked_in'
    ])
    outcsv.writeheader()

    from sked.utils import get_current_event
    for ticket in Ticket.objects.filter(
            event=get_current_event(),
            sale__success=True,
            type__name__contains="Volunteer").order_by('id').select_related():
        outcsv.writerow({
            'ticket_id': ticket.id,
            'first_name': ticket.first_name,
            'last_name': ticket.last_name,
            'organization': ticket.organization,
            'email': ticket.email,
            'checked_in': "Y" if ticket.checked_in else "N"
        })

    return outfile.getvalue()
예제 #22
0
 def get_redirect_url(self, **kwargs):
     return reverse(self.viewname,
                    kwargs={'event_slug': get_current_event().slug})
예제 #23
0
    def handle(self, *args, **options):
        FIELDS = [
            "Prefix", "Middle", "Suffix", "Firstname", "Lastname", "Mailname",
            "Address1", "Address2", "Address3", "City", "State", "Zip",
            "Carrier_rt", "Salutation", "Employer", "Occupation",
            "Organization", "WorkPhone", "WorkExtension", "FaxPhone", "Email",
            "HomePhone", "Phone3", "Phone4", "Phone5", "County", "Precinct",
            "Gender", "Congress", "Statesenate", "Statehouse", "Districta",
            "Districtb", "Districtc", "Party", "Spousename", "Notes", "User1",
            "User2", "User3", "User4", "User5", "User6", "PACname", "CmteID",
            "AskToGive", "AskToRaise", "WebSite", "Email2", "Industry",
            "CandState", "CandID", "CandCycle", "CandDistrict", "CandOffice",
            "Assistant", "Nickname", "Birthdate", "Candname", "Work",
            "Mailname", "Work", "Address1", "Work", "Address2", "Work",
            "Address3", "Work", "City", "Work", "State", "Work", "Zip",
            "contrib_Date", "contrib_Amount", "contrib_Note", "contrib_Check",
            "contrib_Deposit", "contrib_Account", "contrib_Period",
            "contrib_Cycle", "contrib_Member", "contrib_Method",
            "contrib_Source", "contrib_Attribution", "contrib_ReportCode1",
            "contrib_Link", "contrib_Attribution2", "contrib_Batch",
            "contrib_ThankYou", "Twitter", "Subscribe"
        ]
        from sked.utils import get_current_event

        search = {'success': True, 'event': get_current_event()}
        exclude = {}
        if options['exclude_coupon']:
            coupon = CouponCode.objects.get(code=options['exclude_coupon'])
            exclude['coupon_code'] = coupon

        query = Sale.objects.filter(**search)
        if exclude:
            query = query.exclude(**exclude)

        fdomain = '@%s' % options['exclude_domain'] if options[
            'exclude_domain'] else None

        outs = cStringIO.StringIO()
        outc = csv.DictWriter(outs, FIELDS)
        outc.writeheader()

        for sale in query.order_by('id').select_related():
            tickets = list(sale.ticket_set.all())
            if len(tickets) == 0:
                continue

            tk = []
            sale_used = False
            for ticket in tickets:
                if ticket.last_name == sale.last_name and ticket.email == sale.email:
                    # pair them together
                    tk.append({'sale': sale, 'ticket': ticket})
                    sale_used = True
                else:
                    tk.append({'sale': Sale(), 'ticket': ticket})
            if not sale_used and sale.last_name:
                tk.append({'sale': sale, 'ticket': Ticket()})

            for record in tk:
                s = record['sale']
                t = record['ticket']

                if fdomain and (fdomain in s.email or fdomain in t.email):
                    continue

                record = {
                    'Firstname': (t.first_name or s.first_name).encode('utf8'),
                    'Lastname': (t.last_name or s.last_name).encode('utf8'),
                    'Mailname':
                    ' '.join(
                        (s.first_name, s.last_name)).strip().encode('utf8'),
                    'Address1':
                    s.address1.encode('utf8'),
                    'Address2':
                    s.address2.encode('utf8'),
                    'City':
                    s.city.encode('utf8'),
                    'State':
                    s.state.encode('utf8'),
                    'Zip':
                    s.zip,
                    'Employer':
                    t.organization.encode('utf8'),
                    'Organization':
                    t.organization.encode('utf8'),
                    'Occupation':
                    t.title.encode('utf8'),
                    'WebSite':
                    (t.website if
                     ('://' in t.website or not t.website) else 'http://%s' %
                     t.website).encode('utf8'),
                    'Email':
                    t.email or s.email,
                    'Twitter':
                    t.clean_twitter,
                    'Subscribe':
                    'Y' if t.subscribe else 'N',
                    'contrib_Amount':
                    s.amount,
                    'contrib_Date':
                    t.sale.created.strftime("%m/%d/%Y")
                    if t.sale else s.created.strftime("%m/%d/%Y"),
                }
                print s.id or "-", t.id or "-"
                print record
                outc.writerow(record)

        if options['output']:
            f = open(options['output'], 'wb')
            f.write(outs.getvalue())
            f.close()
        else:
            print outs.getvalue()
예제 #24
0
    def handle(self, *args, **options):
        from sked.utils import get_current_event

        search = {'success': True, 'event': get_current_event()}

        query = Ticket.objects.filter(**search)

        fdomain = '@%s' % options['staff_domain'] if options[
            'staff_domain'] else None
        fcoupon = CouponCode.objects.get(
            code=options['staff_coupon']
        ) if options['staff_coupon'] else CouponCode()

        sales = {}
        stats = defaultdict(int)
        coupons = defaultdict(int)
        types = defaultdict(int)
        ambassador = defaultdict(int)
        type_labels = {}
        for ticket in query.order_by('id').select_related():
            sales[ticket.sale.id] = ticket.sale

            stats['tickets'] += 1
            if (ticket.email and fdomain and fdomain in ticket.email) or \
                (ticket.sale.email and fdomain and fdomain in ticket.sale.email) or \
                (ticket.sale.coupon_code and ticket.sale.coupon_code.id == fcoupon.id):
                stats['staff'] += 1
            else:
                stats['non_staff'] += 1
                if ticket.sale.coupon_code:
                    stats['ns_coupon'] += 1
                    coupons[ticket.sale.coupon_code.code] += 1
                types[ticket.type.id] += 1
                type_labels[ticket.type.id] = ticket.type.name

            if ticket.lobby_day:
                stats['lobby_day'] += 1

            ambassador[ticket.ambassador_program] += 1

        print "Total tickets:", stats['tickets']
        print "  Staff:", stats['staff']
        print "  Non-staff:", stats['non_staff']
        print ""

        print "Non-staff tickets by type:"
        for i in sorted(types.keys()):
            print " ", type_labels[i] + ":", types[i]
        print ""
        print "Non-staff tickets purchased with coupons:", stats['ns_coupon']
        for c, num in coupons.items():
            print " ", c + ":", num
        print ""
        print "Lobby day participants:", stats['lobby_day']
        print ""
        print "Ambassador program:"
        for key, label in AMBASSADOR_PROGRAM_CHOICES:
            print " ", label + ":", ambassador[key]
        print ""
        print "Total sales:", sum(
            [float(sale.amount) for sale in sales.values()])
예제 #25
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def register(request):
    if get_current_event().registration_is_open:
        return _open_register(request)
    else:
        return _closed_register(request)
예제 #26
0
파일: views.py 프로젝트: crdunwel/tcamp
 def get_redirect_url(self, **kwargs):
     return reverse(self.viewname, kwargs={'event_slug': get_current_event().slug})
예제 #27
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def save(request):
    if request.method != "POST":
        raise Http404
    try:
        data = json.loads(request.raw_post_data)
    except:
        raise Http404

    sale = Sale()
    out = {"ticket_forms": [], "success": True}
    types = defaultdict(int)
    valid_tickets = []
    for form_id, form_data in data["ticket_forms"].items():
        form_response = {"id": form_id}
        form = TicketForm(form_data)
        if form.is_valid():
            form_response["success"] = True
            valid_tickets.append(form)
            types[int(form_data["type"])] += 1
        else:
            out["success"] = False
            form_response["success"] = False
            form_response["text"] = render_to_string(
                "reg/partials/ticket_form.html", {"ticket_form": form}, context_instance=RequestContext(request)
            )
        out["ticket_forms"].append(form_response)

    if out["success"]:
        # get all the models ready
        sale.event = get_current_event()
        sale.amount = 0
        sale.save()

        tickets = []
        for ticket_form in valid_tickets:
            ticket = ticket_form.save(commit=False)
            ticket.event = get_current_event()
            ticket.sale = sale
            ticket.save()

            tickets.append(ticket)

            if getattr(settings, "SLACK_ENABLED", False):
                try:
                    slack.post_registration(ticket)
                except:
                    pass

        # tickets are good, so confirm price
        price = get_price_data(tickets=types, coupon=data.get("coupon", None))

        # save the coupon code if there is one
        if "coupon" in price:
            sale.coupon_code = CouponCode.objects.get(event=get_current_event(), code=price["coupon"])

        if price["price"] > 0:
            # there should have been a payment form
            form_response = {"success": True}
            payment_form = PaymentForm(data.get("payment_form", {}))
            if payment_form.is_valid():
                # do the prices match?
                if price["price"] != float(data["expected_price"]):
                    # something is wrong
                    payment_form._errors["__all__"] = ErrorList(
                        [u"There was a problem calculating your payment due. Please contact us for further assistance."]
                    )
                    form_response["success"] = False
                else:
                    # moving onward -- update all the sale forms with the relevant fields
                    sale.first_name = payment_form["first_name"].value()
                    sale.last_name = payment_form["last_name"].value()
                    sale.email = payment_form["email"].value()

                    sale.address1 = payment_form["address1"].value()
                    sale.address2 = payment_form["address2"].value()
                    sale.city = payment_form["city"].value()
                    sale.state = payment_form["state"].value()
                    sale.zip = payment_form["zip"].value()

                    sale.amount = price["price"]
                    sale.payment_type = "online_credit"

                    sale.save()

                    # now pay for things
                    result = braintree.Transaction.sale(
                        {
                            "amount": "%.2f" % price["price"],
                            "credit_card": {
                                "number": payment_form["number"].value(),
                                "cvv": payment_form["cvv"].value(),
                                "expiration_month": payment_form["exp_month"].value(),
                                "expiration_year": payment_form["exp_year"].value(),
                            },
                            "options": {"submit_for_settlement": True},
                        }
                    )

                    if result.is_success:
                        # everything is wonderful!
                        # save everything
                        sale.success = True
                        sale.transaction_id = result.transaction.id
                        sale.save()

                        for ticket in tickets:
                            ticket.success = True
                            ticket.save()

                        # Create BOGO coupon for the user, if promotion is ongoing
                        if (
                            "coupon" not in price
                            and datetime.datetime.now()
                            >= datetime.datetime.strptime(settings.BOGO_START_DATE, "%Y-%m-%d")
                            and datetime.datetime.now()
                            <= datetime.datetime.strptime(settings.BOGO_END_DATE, "%Y-%m-%d")
                        ):
                            bogo_code = CouponCode(
                                code="BOGO-{}-{}".format(sale.email, sale.id),
                                discount=100,
                                max_tickets=1,
                                is_staff=False,
                            )
                            bogo_code.save()

                    else:
                        if hasattr(result.transaction, "id"):
                            sale.transaction_id = result.transaction.id
                            sale.save()
                        payment_form._errors["__all__"] = ErrorList(
                            [u"There was a problem processing your payment: %s" % result.message]
                        )
                        form_response["success"] = False
            else:
                form_response["success"] = False

            if not form_response["success"]:
                out["success"] = False
                form_response["text"] = render_to_string(
                    "reg/partials/payment_form.html",
                    {"payment_form": payment_form},
                    context_instance=RequestContext(request),
                )

                # avoid having junk hanging around in the DB
                sale.delete()
            out["payment_form"] = form_response
        else:
            # we can blindly accept all the tickets, since no payment is necessary
            sale.payment_type = "none"
            sale.success = True
            sale.save()

            for ticket in tickets:
                ticket.success = True
                ticket.save()
    else:
        # if they submitted a payment form, validate it anyway so we can offer useful feedback
        if "payment_form" in data:
            payment_form = PaymentForm(data["payment_form"])
            if payment_form.is_valid():
                form_response = {"success": True}
            else:
                form_response = {
                    "success": False,
                    "text": render_to_string(
                        "reg/partials/payment_form.html",
                        {"payment_form": payment_form},
                        context_instance=RequestContext(request),
                    ),
                }
            out["payment_form"] = form_response

    if out["success"]:
        send_sale_email(sale.id)

    return HttpResponse(json.dumps(out), content_type="application/json")
예제 #28
0
class TicketTypeAdmin(EnhancedModelAdminMixin, DefaultFilterMixin,
                      admin.ModelAdmin):
    list_display = ('name', 'event')
    list_filter = ('event', )
    default_filters = (('event__id__exact', lambda: get_current_event().id), )
예제 #29
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def register(request):
    if get_current_event().registration_is_open:
        return _open_register(request)
    else:
        return _closed_register(request)
예제 #30
0
파일: views.py 프로젝트: sunlightlabs/tcamp
def save(request):
    if request.method != "POST":
        raise Http404
    try:
        data = json.loads(request.raw_post_data)
    except:
        raise Http404

    sale = Sale()
    out = {'ticket_forms': [], 'success': True}
    types = defaultdict(int)
    valid_tickets = []
    for form_id, form_data in data['ticket_forms'].items():
        form_response = {'id': form_id}
        form = TicketForm(form_data)
        if form.is_valid():
            form_response['success'] = True
            valid_tickets.append(form)
            types[int(form_data['type'])] += 1
        else:
            out['success'] = False
            form_response['success'] = False
            form_response['text'] = render_to_string(
                'reg/partials/ticket_form.html', {'ticket_form': form},
                context_instance=RequestContext(request))
        out['ticket_forms'].append(form_response)

    if out['success']:
        # get all the models ready
        sale.event = get_current_event()
        sale.amount = 0
        sale.save()

        tickets = []
        for ticket_form in valid_tickets:
            ticket = ticket_form.save(commit=False)
            ticket.event = get_current_event()
            ticket.sale = sale
            ticket.save()

            tickets.append(ticket)

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    slack.post_registration(ticket)
                except:
                    pass

        # tickets are good, so confirm price
        price = get_price_data(tickets=types, coupon=data.get('coupon', None))

        # save the coupon code if there is one
        if 'coupon' in price:
            sale.coupon_code = CouponCode.objects.get(
                event=get_current_event(), code=price['coupon'])

        if price['price'] > 0:
            # there should have been a payment form
            form_response = {'success': True}
            payment_form = PaymentForm(data.get('payment_form', {}))
            if payment_form.is_valid():
                # do the prices match?
                if price['price'] != float(data['expected_price']):
                    # something is wrong
                    payment_form._errors["__all__"] = ErrorList([
                        u"There was a problem calculating your payment due. Please contact us for further assistance."
                    ])
                    form_response['success'] = False
                else:
                    # moving onward -- update all the sale forms with the relevant fields
                    sale.first_name = payment_form['first_name'].value()
                    sale.last_name = payment_form['last_name'].value()
                    sale.email = payment_form['email'].value()

                    sale.address1 = payment_form['address1'].value()
                    sale.address2 = payment_form['address2'].value()
                    sale.city = payment_form['city'].value()
                    sale.state = payment_form['state'].value()
                    sale.zip = payment_form['zip'].value()

                    sale.amount = price['price']
                    sale.payment_type = 'online_credit'

                    sale.save()

                    # now pay for things
                    result = braintree.Transaction.sale({
                        "amount":
                        "%.2f" % price['price'],
                        "credit_card": {
                            "number": payment_form["number"].value(),
                            "cvv": payment_form["cvv"].value(),
                            "expiration_month":
                            payment_form["exp_month"].value(),
                            "expiration_year":
                            payment_form["exp_year"].value()
                        },
                        "options": {
                            "submit_for_settlement": True
                        }
                    })

                    if result.is_success:
                        # everything is wonderful!
                        # save everything
                        sale.success = True
                        sale.transaction_id = result.transaction.id
                        sale.save()

                        for ticket in tickets:
                            ticket.success = True
                            ticket.save()

                        # Create BOGO coupon for the user, if promotion is ongoing
                        if ('coupon' not in price and datetime.datetime.now()
                                >= datetime.datetime.strptime(
                                    settings.BOGO_START_DATE, '%Y-%m-%d')
                                and datetime.datetime.now() <=
                                datetime.datetime.strptime(
                                    settings.BOGO_END_DATE, '%Y-%m-%d')):
                            bogo_code = CouponCode(code='BOGO-{}-{}'.format(
                                sale.email, sale.id),
                                                   discount=100,
                                                   max_tickets=1,
                                                   is_staff=False)
                            bogo_code.save()

                    else:
                        if hasattr(result.transaction, "id"):
                            sale.transaction_id = result.transaction.id
                            sale.save()
                        payment_form._errors["__all__"] = ErrorList([
                            u"There was a problem processing your payment: %s"
                            % result.message
                        ])
                        form_response['success'] = False
            else:
                form_response['success'] = False

            if not form_response['success']:
                out['success'] = False
                form_response['text'] = render_to_string(
                    'reg/partials/payment_form.html',
                    {'payment_form': payment_form},
                    context_instance=RequestContext(request))

                # avoid having junk hanging around in the DB
                sale.delete()
            out['payment_form'] = form_response
        else:
            # we can blindly accept all the tickets, since no payment is necessary
            sale.payment_type = 'none'
            sale.success = True
            sale.save()

            for ticket in tickets:
                ticket.success = True
                ticket.save()
    else:
        # if they submitted a payment form, validate it anyway so we can offer useful feedback
        if 'payment_form' in data:
            payment_form = PaymentForm(data['payment_form'])
            if payment_form.is_valid():
                form_response = {'success': True}
            else:
                form_response = {
                    'success':
                    False,
                    'text':
                    render_to_string('reg/partials/payment_form.html',
                                     {'payment_form': payment_form},
                                     context_instance=RequestContext(request))
                }
            out['payment_form'] = form_response

    if out['success']:
        send_sale_email(sale.id)

    return HttpResponse(json.dumps(out), content_type="application/json")
예제 #31
0
    def handle(self, *args, **options):
        FIELDS = ["Prefix", "Middle", "Suffix", "Firstname", "Lastname", "Mailname", "Address1", "Address2", "Address3", "City", "State", "Zip", "Carrier_rt", "Salutation", "Employer", "Occupation", "Organization", "WorkPhone", "WorkExtension", "FaxPhone", "Email", "HomePhone", "Phone3", "Phone4", "Phone5", "County", "Precinct", "Gender", "Congress", "Statesenate", "Statehouse", "Districta", "Districtb", "Districtc", "Party", "Spousename", "Notes", "User1", "User2", "User3", "User4", "User5", "User6", "PACname", "CmteID", "AskToGive", "AskToRaise", "WebSite", "Email2", "Industry", "CandState", "CandID", "CandCycle", "CandDistrict", "CandOffice", "Assistant", "Nickname", "Birthdate", "Candname", "Work", "Mailname", "Work", "Address1", "Work", "Address2", "Work", "Address3", "Work", "City", "Work", "State", "Work", "Zip", "contrib_Date", "contrib_Amount", "contrib_Note", "contrib_Check", "contrib_Deposit", "contrib_Account", "contrib_Period", "contrib_Cycle", "contrib_Member", "contrib_Method", "contrib_Source", "contrib_Attribution", "contrib_ReportCode1", "contrib_Link", "contrib_Attribution2", "contrib_Batch", "contrib_ThankYou", "Twitter", "Subscribe"]
        from sked.utils import get_current_event

        search = {
            'success': True,
            'event': get_current_event()
        }
        exclude = {}
        if options['exclude_coupon']:
            coupon = CouponCode.objects.get(code=options['exclude_coupon'])
            exclude['coupon_code'] = coupon

        query = Sale.objects.filter(**search)
        if exclude:
            query = query.exclude(**exclude)

        fdomain = '@%s' % options['exclude_domain'] if options['exclude_domain'] else None

        outs = cStringIO()
        outc = csv.DictWriter(outs, FIELDS)
        outc.writeheader()

        for sale in query.order_by('id').select_related():
            tickets = list(sale.ticket_set.all())
            if len(tickets) == 0:
                continue

            tk = []
            sale_used = False
            for ticket in tickets:
                if ticket.last_name == sale.last_name and ticket.email == sale.email:
                    # pair them together
                    tk.append({'sale': sale, 'ticket': ticket})
                    sale_used = True
                else:
                    tk.append({'sale': Sale(), 'ticket': ticket})
            if not sale_used and sale.last_name:
                tk.append({'sale': sale, 'ticket': Ticket()})

            for record in tk:
                s = record['sale']
                t = record['ticket']

                if fdomain and (fdomain in s.email or fdomain in t.email):
                    continue

                record = {
                    'Firstname': (t.first_name or s.first_name).encode('utf8'),
                    'Lastname': (t.last_name or s.last_name).encode('utf8'),
                    'Mailname': ' '.join((s.first_name, s.last_name)).strip().encode('utf8'),
                    'Address1': s.address1.encode('utf8'),
                    'Address2': s.address2.encode('utf8'),
                    'City': s.city.encode('utf8'),
                    'State': s.state.encode('utf8'),
                    'Zip': s.zip,
                    'Employer': t.organization.encode('utf8'),
                    'Organization': t.organization.encode('utf8'),
                    'Occupation': t.title.encode('utf8'),
                    'WebSite': (t.website if ('://' in t.website or not t.website) else 'http://%s' % t.website).encode('utf8'),
                    'Email': t.email or s.email,
                    'Twitter': t.clean_twitter,
                    'Subscribe': 'Y' if t.subscribe else 'N',
                    'contrib_Amount': s.amount,
                    'contrib_Date': t.sale.created.strftime("%m/%d/%Y") if t.sale else s.created.strftime("%m/%d/%Y"),
                }
                print(s.id or "-", t.id or "-")
                print(record)
                outc.writerow(record)

        if options['output']:
            f = open(options['output'], 'wb')
            f.write(outs.getvalue())
            f.close()
        else:
            print(outs.getvalue())
예제 #32
0
    def handle(self, *args, **options):
        from sked.utils import get_current_event

        search = {
            'success': True,
            'event': get_current_event()
        }

        query = Ticket.objects.filter(**search)

        fdomain = '@%s' % options['staff_domain'] if options['staff_domain'] else None
        fcoupon = CouponCode.objects.get(code=options['staff_coupon']) if options['staff_coupon'] else CouponCode()

        sales = {}
        stats = defaultdict(int)
        coupons = defaultdict(int)
        types = defaultdict(int)
        ambassador = defaultdict(int)
        type_labels = {}
        for ticket in query.order_by('id').select_related():
            sales[ticket.sale.id] = ticket.sale

            stats['tickets'] += 1
            if (ticket.email and fdomain and fdomain in ticket.email) or \
                (ticket.sale.email and fdomain and fdomain in ticket.sale.email) or \
                (ticket.sale.coupon_code and ticket.sale.coupon_code.id == fcoupon.id):
                    stats['staff'] += 1
            else:
                stats['non_staff'] += 1
                if ticket.sale.coupon_code:
                    stats['ns_coupon'] += 1
                    coupons[ticket.sale.coupon_code.code] += 1
                types[ticket.type.id] += 1
                type_labels[ticket.type.id] = ticket.type.name

            if ticket.lobby_day:
                stats['lobby_day'] += 1

            ambassador[ticket.ambassador_program] += 1



        print "Total tickets:", stats['tickets']
        print "  Staff:", stats['staff']
        print "  Non-staff:", stats['non_staff']
        print ""

        print "Non-staff tickets by type:"
        for i in sorted(types.keys()):
            print " ", type_labels[i] + ":", types[i]
        print ""
        print "Non-staff tickets purchased with coupons:", stats['ns_coupon']
        for c, num in coupons.items():
            print " ", c + ":", num
        print ""
        print "Lobby day participants:", stats['lobby_day']
        print ""
        print "Ambassador program:"
        for key, label in AMBASSADOR_PROGRAM_CHOICES:
            print " ", label + ":", ambassador[key]
        print ""
        print "Total sales:", sum([float(sale.amount) for sale in sales.values()])