Ejemplo n.º 1
0
def switch_pay(request):
    """
    This view lets accountants switch member signature info
    has their signature arrived?
    """
    speed_id = request.matchdict['ticket_id']
    dashboard_page = request.cookies['on_page']
    _entry = PartyTicket.get_by_id(speed_id)

    if _entry.payment_received is True:  # change to NOT SET
        _entry.payment_received = False
        _entry.payment_received_date = datetime(1970, 1, 1)
    elif _entry.payment_received is False:  # set to NOW
        _entry.payment_received = True
        _entry.payment_received_date = datetime.now()

#    log.info(
#        "payment info of speedfunding.id %s changed by %s to %s" % (
#            _entry.id,
#            request.user.login,
#            _entry.payment_received
#        )
#    )
    return HTTPFound(
        request.route_url('dashboard',
                          number=dashboard_page,))
Ejemplo n.º 2
0
def get_ticket(request):
    """
    this view gives a user access to her ticket via URL with code
    the response is a PDF download
    """
    _code = request.matchdict['code']
    _email = request.matchdict['email']
    _ticket = PartyTicket.get_by_code(_code)
    if isinstance(_ticket, NoneType):
        return HTTPFound(location=request.route_url('party'))
    if not (_ticket.email == _email):
        #print("no match!")
        return HTTPFound(location=request.route_url('party'))

    # prepare ticket URL with email & code
    # 'https://events.c3s.cc/ci/p1402/' + _ticket.email + _ticket.email_confirm_code
    # 'https://192.168.2.128:6544/ci/p1402/' + _ticket.email + _ticket.email_confirm_code
    _url = request.registry.settings[
        'c3spartyticketing.url'] + '/ci/p1402/' + _ticket.email_confirm_code

    # return a pdf file
    pdf_file = make_qr_code_pdf(_ticket, _url)
    response = Response(content_type='application/pdf')
    pdf_file.seek(0)  # rewind to beginning
    response.app_iter = open(pdf_file.name, "r")
    return response
Ejemplo n.º 3
0
def delete_entry(request):
    """
    This view lets accountants delete entries (doublettes)
    """
    _id = request.matchdict['ticket_id']
    dashboard_page = request.cookies['on_page']
    _entry = PartyTicket.get_by_id(_id)

    PartyTicket.delete_by_id(_entry.id)
    log.info(
        "entry.id %s was deleted by %s" % (_entry.id,
                                           request.user.login,)
    )
    return HTTPFound(
        request.route_url('dashboard',
                          number=dashboard_page,))
Ejemplo n.º 4
0
def list_codes(request):
    """
    return the list of codes
    """
    if 'localhost' not in request.host:
        return 'foo'
    codes = PartyTicket.get_all_codes()
    return codes
Ejemplo n.º 5
0
 def test_generate_qr_code(self):
     """
     Test QR-Code generation
     """
     from c3spartyticketing.utils import make_qr_code_pdf
     _ticket = PartyTicket.get_by_id(1)
     result = make_qr_code_pdf(
         _ticket,
         "http://192.168.2.128:6544/ci/p1402/ABCDEFGBAR")
     result
Ejemplo n.º 6
0
def make_random_string():
    """
    used as email confirmation code
    """
    randomstring = ''.join(
        random.choice(
            string.ascii_uppercase + string.digits
        ) for x in range(10))
    # check if confirmation code is already used
    print(
        "checking if ex. conf"
        ".code: %s" % PartyTicket.check_for_existing_confirm_code(
            randomstring))
    while (PartyTicket.check_for_existing_confirm_code(randomstring)):
            # create a new one, if the new one already exists in the database
            print("generating new code")
            randomstring = make_random_string()  # pragma: no cover

    return randomstring
Ejemplo n.º 7
0
def give_ticket(request):
    """
    this view gives a user access to her ticket via URL with code
    the response is a PDF download
    """
    _code = request.matchdict['code']
    _ticket = PartyTicket.get_by_code(_code)
#    _url = 'https://events.c3s.cc/ci/p1402/' + _ticket.email_confirm_code
#    _url = 'https://192.168.2.128:6544/ci/p1402/' + _ticket.email_confirm_code
    _url = request.registry.settings[
        'c3spartyticketing.url'] + '/ci/p1402/' + _ticket.email_confirm_code
    # return a pdf file
    pdf_file = make_qr_code_pdf(_url)
    response = Response(content_type='application/pdf')
    pdf_file.seek(0)  # rewind to beginning
    response.app_iter = open(pdf_file.name, "r")
    return response
Ejemplo n.º 8
0
def ticket_detail(request):
    """
    This view lets accountants view ticket order details
    how about the payment?
    """
    # check if staffer wanted to look at specific ticket id
    tid = request.matchdict['ticket_id']
    #log.info("the id: %s" % tid)

    _ticket = PartyTicket.get_by_id(tid)

    #print(_speedfunding)
    if _ticket is None:  # that speed_id did not produce good results
        return HTTPFound(  # back to base
            request.route_url('dashboard',
                              number=0,))

    class ChangeDetails(colander.MappingSchema):
        """
        colander schema (form) to change details of speedfunding
        """
        payment_received = colander.SchemaNode(
            colander.Bool(),
            title=_(u"Zahlungseingang melden?")
        )

    schema = ChangeDetails()
    form = deform.Form(
        schema,
        buttons=[
            deform.Button('submit', _(u'Submit')),
            deform.Button('reset', _(u'Reset'))
        ],
        #use_ajax=True,
        #renderer=zpt_renderer
    )

    # if the form has been used and SUBMITTED, check contents
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure, e:  # pragma: no cover
            log.info(e)
            #print("the appstruct from the form: %s \n") % appstruct
            #for thing in appstruct:
            #    print("the thing: %s") % thing
            #    print("type: %s") % type(thing)
            print(e)
            #message.append(
            request.session.flash(
                _(u"Please note: There were errors, "
                  "please check the form below."),
                'message_above_form',
                allow_duplicate=False)
            return{'form': e.render()}

        # change info about speedfunding in database ?
        same = (  # changed value through form (different from db)?
            appstruct['payment_received'] == _ticket.payment_received)
        if not same:
            log.info(
                "info about payment of %s changed by %s to %s" % (
                    _ticket.id,
                    request.user.login,
                    appstruct['payment_received']))
            _ticket.payment_received = appstruct['payment_received']
            if _ticket.payment_received is True:
                _ticket.payment_received_date = datetime.now()
            else:
                _ticket.payment_received_date = datetime(
                    1970, 1, 1)
        # store appstruct in session
        request.session['appstruct'] = appstruct

        # show the updated details
        HTTPFound(route_url('detail', request, ticket_id=_ticket.id))
Ejemplo n.º 9
0
def send_ticket_mail_view(request):
    """
    this view sends a mail to the user with ticket links
    """
    _id = request.matchdict['ticket_id']
    _ticket = PartyTicket.get_by_id(_id)
    if isinstance(_ticket, NoneType):
        return HTTPFound(
            request.route_url(
                'dashboard',
                number=request.cookies['on_page'],
                order=request.cookies['order'],
                orderby=request.cookies['orderby'],
            )
        )

    mailer = get_mailer(request)
    body_lines = (  # a list of lines
        u'''Hallo ''', _ticket.firstname, ' ', _ticket.lastname, u''' !

Wir haben Deine Überweisung erhalten. Dankeschön!

Es gibt mehrere Möglichkeiten, das Ticket mitzubringen:

1) Lade jetzt dein Ticket herunter und drucke es aus.
   Wir scannen dann am Eingang den QR-Code und du bist drin.

   ''', request.route_url('get_ticket',
                          email=_ticket.email,
                          code=_ticket.email_confirm_code), u'''

2) Lade die mobile version für dein Smartphone (oder Tablet).

   ''', request.route_url('get_ticket_mobile',
                          email=_ticket.email,
                          code=_ticket.email_confirm_code), u'''

3) Bringe einfach diesen Code mit: ''' + _ticket.email_confirm_code + u'''

Damit können wir dich am Eingang wiedererkennen. Falls Du ein Ticket für
*mehrere Personen* bestellt hast, kannst Du diesen Code an diese Personen
weiterreichen. Aber Vorsicht! Wir zählen mit! ;-)

Bis bald!

Dein C3S-Team''',
    )
    the_mail_body = ''.join([line for line in body_lines])
    the_mail = Message(
        subject=_(u"C3S Party-Ticket: bitte herunterladen!"),
        sender="*****@*****.**",
        recipients=[_ticket.email],
        body=the_mail_body
    )
    from smtplib import SMTPRecipientsRefused
    try:
        #mailer.send(the_mail)
        mailer.send_immediately(the_mail, fail_silently=False)
        #print(the_mail.body)
        _ticket.ticketmail_sent = True
        _ticket.ticketmail_sent_date = datetime.now()

    except SMTPRecipientsRefused:  # folks with newly bought tickets (no mail)
        print('SMTPRecipientsRefused')
        return HTTPFound(
            request.route_url('dashboard', number=request.cookies['on_page'],))

    # 'else': send user to the form
    return HTTPFound(request.route_url('dashboard',
                                       number=request.cookies['on_page'],
                                       #order=request.cookies['order'],
                                       #orderby=request.cookies['orderby'],
                                       )
                     )
Ejemplo n.º 10
0
def make_hobo_view(request):
    """
    this view adds schwarzfahrers to the gästeliste
    """
    class PersonalData(colander.MappingSchema):
        """
        colander schema for membership application form
        """
        locale_name = 'de'
        firstname = colander.SchemaNode(
            colander.String(),
            title=_(u"Vorame"),
            oid="firstname",
        )
        lastname = colander.SchemaNode(
            colander.String(),
            title=_(u"Nachname"),
            oid="lastname",
        )
        email = colander.SchemaNode(
            colander.String(),
            title=_(u'Email'),
            validator=colander.Email(),
            oid="email",
        )
        comment = colander.SchemaNode(
            colander.String(),
            title=_("Warum Schwarzfahren?"),
            missing='',
            validator=colander.Length(max=250),
            widget=deform.widget.TextAreaWidget(rows=3, cols=50),
            description=_(u"(guter grund) (255 Zeichen)"),
            oid="comment",
        )
        _LOCALE_ = colander.SchemaNode(
            colander.String(),
            widget=deform.widget.HiddenWidget(),
            default=locale_name
        )

    class HoboForm(colander.Schema):
        """
        The Form consists of
        - Personal Data
        - Ticketing Information
        - FoodInfo
        """
        person = PersonalData(
            title=_(u"Persönliche Daten"),
            #description=_(u"this is a test"),
            #css_class="thisisjustatest"
        )

    schema = HoboForm()

    form = deform.Form(
        schema,
        buttons=[
            deform.Button('submit', _(u'Absenden')),
            deform.Button('reset', _(u'Zurücksetzen'))
        ],
        #use_ajax=True,
        renderer=zpt_renderer
    )

    if 'submit' in request.POST:
        print "new hobo!?!"
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
            print('validated!')
            the_total = 0  # nothing to pay
            # create an appstruct for persistence
            randomstring = make_random_string()
            hobo = PartyTicket(
                firstname=appstruct['person']['firstname'],
                lastname=appstruct['person']['lastname'],
                email=appstruct['person']['email'],
                password='',  # appstruct['person']['password'],
                locale=appstruct['person']['_LOCALE_'],
                email_is_confirmed=False,
                email_confirm_code=randomstring,
                date_of_submission=datetime.now(),
                num_tickets=1,
                ticket_type=5,
                the_total=the_total,
                user_comment=appstruct['person']['comment'],
            )
            hobo.payment_received = True
            dbsession = DBSession
            #try:
            print "about to add ticket"
            dbsession.add(hobo)
            dbsession.flush()
            print "added ticket"
            #except InvalidRequestError, e:  # pragma: no cover
            #    print("InvalidRequestError! %s") % e
            #except IntegrityError, ie:  # pragma: no cover
            #print("IntegrityError! %s") % ie
            return HTTPFound(
                request.route_url('detail',
                                  ticket_id=hobo.id)
            )

        except ValidationFailure, e:
            return {
                'hoboform': e.render()
            }
Ejemplo n.º 11
0
def stats_view(request):
    """
    This view lets accountants view statistics:
    how many tickets of which category, payment status, etc.
    """
    #print("who is it? %s" % request.user.login)
    _number_of_datasets = PartyTicket.get_number()
    _number_of_tickets = PartyTicket.get_num_tickets()
    _num_passengers = PartyTicket.num_passengers()
    _num_open_tickets = int(_number_of_tickets) - int(_num_passengers)
    _num_tickets_unpaid = PartyTicket.get_num_unpaid()
    #
    _num_hobos = PartyTicket.get_num_hobos()
    _num_class_2 = PartyTicket.get_num_class_2()
    _num_class_2_food = PartyTicket.get_num_class_2_food()
    _num_class_1 = PartyTicket.get_num_class_1()
    _num_class_green = PartyTicket.get_num_class_green()
    #
    _sum_tickets_total = PartyTicket.get_sum_tickets_total()
    _sum_tickets_paid = PartyTicket.get_sum_tickets_paid()
    _sum_tickets_unpaid = PartyTicket.get_sum_tickets_unpaid()

    return {
        '_number_of_datasets': _number_of_datasets,
        '_number_of_tickets': _number_of_tickets,
        '_num_passengers': _num_passengers,
        '_num_open_tickets': _num_open_tickets,
        '_num_tickets_unpaid': _num_tickets_unpaid,
        # ticket categories
        'num_hobos': _num_hobos,
        'num_class_2': _num_class_2,
        'num_class_2_food': _num_class_2_food,
        'num_class_1': _num_class_1,
        'num_class_green': _num_class_green,
        # focus on cash
        'sum_tickets_total': _sum_tickets_total,
        'sum_tickets_paid': _sum_tickets_paid,
        'sum_tickets_unpaid': _sum_tickets_unpaid,
    }
Ejemplo n.º 12
0
def accountants_desk(request):
    """
    This view lets accountants view applications and set their status:
    has their payment arrived?
    """
    #print("who is it? %s" % request.user.login)
    _number_of_datasets = PartyTicket.get_number()
    #print("request.matchdict['number']: %s" % request.matchdict['number'])
    try:  # check if
        # a page number was supplied with the URL
        _page_to_show = int(request.matchdict['number'])
        #print("page to show: %s" % _page_to_show)
    except:
        _page_to_show = 0
    # is it a number? yes, cast above
    #if not isinstance(_page_to_show, type(1)):
    #    _page_to_show = 0
    #print("_page_to_show: %s" % _page_to_show)

    # check for input from "find dataset by confirm code" form
    if 'code_to_show' in request.POST:
        print("found code_to_show in POST: %s" % request.POST['code_to_show'])
        try:
            _code = request.POST['code_to_show']
            #print(_code)
            _entry = PartyTicket.get_by_code(_code)
            print(_entry)
            print(_entry.id)

            return HTTPFound(
                location=request.route_url(
                    'detail',
                    ticket_id=_entry.id)
            )
        except:
            # choose default
            print("barf!")
            pass

    # how many to display on one page?
    """
    num_display determines how many items are to be shown on one page
    """
    #print request.POST
    if 'num_to_show' in request.POST:
        #print("found it in POST")
        try:
            _num = int(request.POST['num_to_show'])
            if isinstance(_num, type(1)):
                num_display = _num
        except:
            # choose default
            num_display = 20
    elif 'num_display' in request.cookies:
        #print("found it in cookie")
        num_display = int(request.cookies['num_display'])
    else:
        #print("setting default")
        num_display = request.registry.settings[
            'c3spartyticketing.dashboard_number']
    #print("num_display: %s " % num_display)

    """
    base_offset helps us to minimize impact on the database
    when querying for results.
    we can choose just those results we need for the page to show
    """
    #try:
    base_offset = int(_page_to_show) * int(num_display)
    #print("base offset: %s" % base_offset)
    #except:
    #    base_offset = 0
    #    if 'base_offset' in request.session:
    #        base_offset = request.session['base_offset']
    #    else:
    #        base_offset = request.registry.settings['speedfunding.offset']

    # get data sets from DB
    _tickets = PartyTicket.ticket_listing(
        PartyTicket.id.desc(), how_many=num_display, offset=base_offset)

    # calculate next-previous-navi
    next_page = (int(_page_to_show) + 1)
    if (int(_page_to_show) > 0):
        previous_page = int(_page_to_show) - 1
    else:
        previous_page = int(_page_to_show)

    # store info about current page in cookie
    request.response.set_cookie('on_page', value=str(_page_to_show))
    #print("num_display: %s" % num_display)
    request.response.set_cookie('num_display', value=str(num_display))

    #
    # prepare the autocomplete form for codes
    #
    # get codes from another view via subrequest, see
    # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/subrequest.html
    subreq = Request.blank('/all_codes')  # see http://0.0.0.0:6543/all_codes
    response = request.invoke_subrequest(subreq)
    #print("the subrequests response: %s" % response.body)
    #import requests
    #r = requests.get('http://0.0.0.0:6543/all_codes')
    #the_codes = json.loads(r.text)  # gotcha: json needed!
    the_codes = json.loads(response.body)  # gotcha: json needed!

    my_autoc_wid = deform.widget.AutocompleteInputWidget(
        min_length=1,
        title="widget title",
        values=the_codes,
    )

    # prepare a form for autocomplete search for codes.
    class CodeAutocompleteForm(colander.MappingSchema):
        """
        colander schema to make deform autocomplete form
        """
        code_to_show = colander.SchemaNode(
            colander.String(),
            title="Search entry (autocomplete)",
            validator=colander.Length(min=1, max=8),
            widget=my_autoc_wid,
            description='start typing. use arrows. press enter. twice.'

        )

    schema = CodeAutocompleteForm()
    form = deform.Form(
        schema,
        buttons=('go!',),
        #use_ajax=True,  # <-- whoa!
        renderer=zpt_renderer,
    )
    autoformhtml = form.render()

    return {'_number_of_datasets': _number_of_datasets,
            'tickets': _tickets,
            'num_display': num_display,
            'next': next_page,
            'previous': previous_page,
            'autoform': autoformhtml,
            }
Ejemplo n.º 13
0
def party_view(request):
    """
    the view users use to order a ticket
    """
    _num_tickets = PartyTicket.get_num_tickets()
    _num_tickets_paid = PartyTicket.get_num_tickets_paid()

    class PersonalData(colander.MappingSchema):
        """
        colander schema for membership application form
        """
        locale_name = get_locale_name(request)
        firstname = colander.SchemaNode(
            colander.String(),
            title=_(u"Vorame"),
            oid="firstname",
        )
        lastname = colander.SchemaNode(
            colander.String(),
            title=_(u"Nachname"),
            oid="lastname",
        )
        email = colander.SchemaNode(
            colander.String(),
            title=_(u'Email'),
            validator=colander.Email(),
            oid="email",
        )
        # password = colander.SchemaNode(
        #     colander.String(),
        #     validator=colander.Length(min=3, max=100),
        #     widget=deform.widget.PasswordWidget(size=20),
        #     title=_(u"Password (to protect access to your data)"),
        #     description=_("We need a password to protect your data. After "
        #                   "verifying your email you will have to enter it."),
        #     oid="password",
        # )
        comment = colander.SchemaNode(
            colander.String(),
            title=_("Kommentare"),
            missing='',
            validator=colander.Length(max=250),
            widget=deform.widget.TextAreaWidget(rows=3, cols=50),
            description=_(u"Raum für Kommentare (255 Zeichen)"),
            oid="comment",
        )
        _LOCALE_ = colander.SchemaNode(
            colander.String(),
            widget=deform.widget.HiddenWidget(),
            default=locale_name
        )

    num_ticket_options = (
        ('10', _(u'10 tickets')),
        ('9', _(u'9 tickets')),
        ('8', _(u'8 tickets')),
        ('7', _(u'7 tickets')),
        ('6', _(u'6 tickets')),
        ('5', _(u'5 tickets')),
        ('4', _(u'4 tickets')),
        ('3', _(u'3 tickets')),
        ('2', _(u'2 tickets')),
        ('1', _(u'1 tickets')),
        #('0', _(u'no ticket')),
    )
    ticket_type_options = (
        (1, _(u'2. Klasse (5€: party, bands)')),
        (2, _(u'2. Klasse + Speisewagen (15€: party, bands, essen)')),
        (3, _(u'1. Klasse (50€: party, bands, essen, kaffee, shirt)')),
        (4, _(u'Grüne Mamba (100€: party, bands, essen, kaffee, jacke)')),
    )

    class PartyTickets(colander.MappingSchema):

        ticket_type = colander.SchemaNode(
            colander.Integer(),
            title=_(u"Ich reise in der folgenden Kategorie:"),
            description=_(
                u'Du kannst uns mit dem Kauf von Tickets unterstützen. '
                u'Überschüsse fliessen in die Büroausstattung.'),
            default="1",
            widget=deform.widget.RadioChoiceWidget(
                size=1, css_class='ticket_types_input',
                values=ticket_type_options,
                #inline=True
            ),
            oid="ticket_type"
        )
        num_tickets = colander.SchemaNode(
            colander.Integer(),
            title=_(u"Ich nehme die folgende Anzahl von Tickets"),
            description=_(
                u'Du kannst zwischen 1 und 10 Tickets bestellen. '
                u'Die Kosten variieren je nach Ticket-Kategorie.'),
            default="1",
            widget=deform.widget.SelectSliderWidget(
                #size=3, css_class='num_tickets_input',
                values=num_ticket_options),
            validator=colander.Range(
                min=1,
                max=10,
                min_err=_(u"Du brauchst mindestens ein Ticket, "
                          u"um die Reise anzutreten."),
                max_err=_(u"Höchstens 10 Tickets. (viel los!)"),
            ),
            oid="num_tickets")

    class TicketForm(colander.Schema):
        """
        The Form consists of
        - Personal Data
        - Ticketing Information
        - FoodInfo
        """
        person = PersonalData(
            title=_(u"Persönliche Daten"),
            #description=_(u"this is a test"),
            #css_class="thisisjustatest"
        )
        ticket_info = PartyTickets(
            title=_(u"Ticketinformationen")
        )
        #shares = FoodInfo(
        #    title=_(u"Food Stamps")
        #)

    schema = TicketForm()

    form = deform.Form(
        schema,
        buttons=[
            deform.Button('submit', _(u'Absenden')),
            deform.Button('reset', _(u'Zurücksetzen'))
        ],
        use_ajax=True,
        renderer=zpt_renderer
    )

    # if the form has NOT been used and submitted, remove error messages if any
    if not 'submit' in request.POST:
        request.session.pop_flash()

    # if the form has been used and SUBMITTED, check contents
    if 'submit' in request.POST:
        print "submitted!"
        controls = request.POST.items()
        print controls
        try:
            print 'about to validate form input'
            appstruct = form.validate(controls)
            print 'done validating form input'
            print("the appstruct from the form: %s \n") % appstruct
            for thing in appstruct:
                print("the thing: %s") % thing
                print("type: %s") % type(thing)

        except ValidationFailure, e:
            print(e)
            request.session.flash(
                _(u"Please note: There were errors, "
                  "please check the form below."),
                'message_above_form',
                allow_duplicate=False)
            return{
                'form': e.render(),
                '_num_tickets': _num_tickets,
                '_num_tickets_paid': _num_tickets_paid,
            }

        # make confirmation code
        randomstring = make_random_string()

        # calculate the total sum
        the_value = {
            1: 5,
            2: 15,
            3: 50,
            4: 100,
        }
        _the_total = appstruct['ticket_info']['num_tickets'] * the_value.get(
            appstruct['ticket_info']['ticket_type'])
        appstruct['ticket_info']['the_total'] = _the_total
        print("_the_total: %s" % _the_total)
        # to store the data in the DB, an object is created
        ticket = PartyTicket(
            firstname=appstruct['person']['firstname'],
            lastname=appstruct['person']['lastname'],
            email=appstruct['person']['email'],
            password='',  # appstruct['person']['password'],
            locale=appstruct['person']['_LOCALE_'],
            email_is_confirmed=False,
            email_confirm_code=randomstring,
            date_of_submission=datetime.now(),
            num_tickets=appstruct['ticket_info']['num_tickets'],
            ticket_type=appstruct['ticket_info']['ticket_type'],
            the_total=_the_total,
            user_comment=appstruct['person']['comment'],
        )
        dbsession = DBSession
        try:
            print "about to add ticket"
            dbsession.add(ticket)
            print "adding ticket"
            appstruct['email_confirm_code'] = randomstring  # XXX
            appstruct['email_confirm_code'] = randomstring
        except InvalidRequestError, e:  # pragma: no cover
            print("InvalidRequestError! %s") % e
Ejemplo n.º 14
0
def new_ticket(request):
    """
    This view lets cachiers make/issue new tickets

    a form permits checkin of people, up to the amount of tickets
    """
    logged_in = authenticated_userid(request)
    print("authenticated_userid: " + str(logged_in))

    print("the request.POST: %s" % request.POST)
    add_cond = ('persons' in request.POST)
    if add_cond:
        _num = request.POST['persons']
        if 'type1' in request.POST:
            _type = request.POST['type1']
            _type_int = 1
            _type_cost = 5
        elif 'type2' in request.POST:
            _type = request.POST['type2']
            _type_int = 2
            _type_cost = 15
        elif 'type3' in request.POST:
            _type = request.POST['type3']
            _type_int = 3
            _type_cost = 50
        elif 'type4' in request.POST:
            _type = request.POST['type4']
            _type_int = 4
            _type_cost = 100
        log.info(
            "%s tickets(s) of cat. %s sold by %s" % (_num, _type, logged_in))
        _new = PartyTicket(
            firstname='anon',
            lastname='anon',
            email='anon',
            password='******',
            locale='de',
            email_is_confirmed=False,
            email_confirm_code='cash',
            num_tickets=int(_num),
            ticket_type=_type_int,
            the_total=int(_num)*_type_cost,
            user_comment='got ticket at entry',
            date_of_submission=datetime.now(),
            payment_received=True
        )
        #try:
        dbsession = DBSession()
        _new.payment_received = True
        #import pdb
        #pdb.set_trace()
        _new.checked_persons = int(_num)
        _new.payment_received_date = datetime.now()
        _new.email_confirm_code = 'CASHDESK' + make_random_string()
        _new.accountant_comment = 'issued by %s' % logged_in
        dbsession.add(_new)

        #except:
        #    print("new_ticket: something went wrong")
            #pass
    _num_passengers = PartyTicket.num_passengers()
    _num_open_tickets = int(
        PartyTicket.get_num_tickets()) - int(_num_passengers)

    return {
        'logged_in': logged_in,
        'num_passengers': _num_passengers,
        'num_open_tickets': _num_open_tickets,
    }
Ejemplo n.º 15
0
def kasse(request):
    """
    This view lets cachiers do stuff
    """
    logged_in = authenticated_userid(request)
    print("authenticated_userid: " + str(logged_in))
    #log.info("check in conducted by %s" % logged_in)

    # check for input from "find dataset by confirm code" form
    if 'code_to_show' in request.POST:
        print("found code_to_show in POST: %s" % request.POST['code_to_show'])
        try:
            _code = request.POST['code_to_show']
            #print(_code)
            _entry = PartyTicket.get_by_code(_code)
            print(_entry)
            print(_entry.id)

            return HTTPFound(
                location=request.route_url(
                    'check_in',
                    event='p1402',
                    code=_entry.email_confirm_code)
            )
        except:
            # choose default
            print("barf!")
            request.session.flash('gleis 16 gibt es garnicht!')
            pass

    # prepare the autocomplete form with codes
    # get codes from another view via subrequest, see
    # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/subrequest.html
    subreq = Request.blank('/all_codes')  # see http://0.0.0.0:6543/all_codes
    response = request.invoke_subrequest(subreq)
    the_codes = json.loads(response.body)  # gotcha: json needed!

    my_autoc_wid = deform.widget.AutocompleteInputWidget(
        min_length=1,
        title="widget title",
        values=the_codes,
    )

    # prepare a form for autocomplete search for codes.
    class CodeAutocompleteForm(colander.MappingSchema):
        """
        colander schema to make deform autocomplete form
        """
        code_to_show = colander.SchemaNode(
            colander.String(),
            title="Code eingeben (autocomplete)",
            validator=colander.Length(min=1, max=8),
            widget=my_autoc_wid,
            description='start typing. use arrows. press enter. twice.'

        )

    schema = CodeAutocompleteForm()
    form = deform.Form(
        schema,
        buttons=('go!',),
        #use_ajax=True,  # <-- whoa!
        #renderer=zpt_renderer,
    )
    autoformhtml = form.render()

    _num_passengers = PartyTicket.num_passengers()
    _num_open_tickets = int(
        PartyTicket.get_num_tickets()) - int(_num_passengers)

    return {
        'autoform': autoformhtml,
        'logged_in': logged_in,
        'num_passengers': _num_passengers,
        'num_open_tickets': _num_open_tickets
    }
Ejemplo n.º 16
0
def check_in(request):
    """
    This view lets cachiers log in people

    a form permits checkin of people, up to the amount of tickets
    """
    logged_in = authenticated_userid(request)
    print("authenticated_userid: " + str(logged_in))
    log.info("check in conducted by %s" % logged_in)

    # check for input from checkin function POST
    #print(request.POST)
    # MultiDict([('persons', u'10'),
    #            ('checkin', u'Check in!'),
    #            ('code', u'ABCDEFGHIJ')])
    __check = ('checkin' in request.POST)
    __code = ('code' in request.POST)
    __personen = ('persons' in request.POST)
    if __check and __code and __personen:
        #print("############# check_in_cond is True.")
        _code = request.POST['code']
        _persons = request.POST['persons']
        _ticket = PartyTicket.get_by_code(_code)
        if isinstance(_ticket, NoneType):
            "if the ticket code was not found, return to base"
            request.session.flash('code not found. gleis 16 gibt es nicht.')
            return HTTPFound(
                location=request.route_url('kasse'))
        _ticket.checkin_time = datetime.now()
        #_ticket.checkin_seen = True
        _ticket.checked_persons += int(_persons)

    _num_passengers = PartyTicket.num_passengers()
    _num_open_tickets = int(
        PartyTicket.get_num_tickets()) - int(_num_passengers)

    '''
    checkin was called from a prepared URL ('/ci/{event}/{code}')
    '''
    _code = request.matchdict['code']
    # get dataset from db
    _ticket = PartyTicket.get_by_code(_code)
    if isinstance(_ticket, NoneType):  # not found
        print("ticket not found!?!")
        return {
            'logged_in': logged_in,
            'status': 'NOT FOUND',
            'code': '',
            'paid': 'Nein',
            'num_passengers': _num_passengers,
            'num_open_tickets': _num_open_tickets,
        }
    else:
        print("the ticket: %s" % _ticket)
        pass

    '''
    users may pay at the counter,
    if they forgot to transfer (and room is not full)
    '''
    if 'Bezahlt' in request.POST:
        _ticket.payment_received = True
        _ticket.payment_received_date = datetime.now()

    # types of tickets displayed in the backend
    ticket_type_options = {
        1: _(u'2. Klasse'),
        2: _(u'2. Klasse + Speisewagen'),
        3: _(u'1. Klasse'),
        4: _(u'Grüne Mamba'),
    }

    _klass = ticket_type_options.get(_ticket.ticket_type)
    _vacancies = _ticket.num_tickets - _ticket.checked_persons

    return {
        'vacancies': _vacancies,  # the free tickets of this visitor
        'logged_in': logged_in,
        'num_passengers': _num_passengers,
        'num_open_tickets': _num_open_tickets,
        'code': _code,
        'klass': _klass,
        'paid': _ticket.payment_received,
        'ticket': _ticket,
    }