Exemplo n.º 1
0
def store_registration(mailer, session, data):
    """
    Stores a registration to the database.

    The *data* dictionary contains the following items (all strings):

        * group_name
        * contact_name
        * email
        * tel
        * time: The time of day that the group begins the "run".
        * comments
        * num_vegetarians
        * num_participants
        * user_id: The ID of the user that made the registration
    """
    qry = Group.query.filter_by(name=data['group_name'])
    check = qry.first()
    if check:
        raise ValueError('Group {} already registered'.format(
            data['group_name']))
    else:
        key = os.urandom(50).encode('base64').replace('/', '')[0:20]
        # Regenerate keys if needed (just in case to avoid duplicates).
        qry = Group.query.filter_by(confirmation_key=key)
        check_key = qry.first()
        while check_key:
            key = os.urandom(50).encode('base64').replace('/', '')[0:20]
            qry = Group.query.filter_by(confirmation_key=key)
            check_key = qry.first()

        new_grp = Group(data['group_name'],
                        data['contact_name'],
                        data['tel'],
                        None,
                        data['time'],
                        data['comments'],
                        key,
                        data['user_id'])
        order = start_time_to_order(data['time'])
        new_grp.order = _get_unique_order(Group, order)
        new_grp.num_vegetarians = int(data['num_vegetarians'])
        new_grp.num_participants = int(data['num_participants'])
        new_grp.email = data['email']

        session.add(new_grp)
        try:
            session.flush()
        except IntegrityError:
            session.rollback()
            LOG.exception('Error while adding the new group {0}'.format(
                data['group_name']))
            raise ValueError('Error while adding the new group {0}'.format(
                data['group_name']))

        return key
Exemplo n.º 2
0
def stats(conf):
    """
    Fetch some basic stats from the system.
    """
    num_groups = Group.all().count()
    num_slots = len(TimeSlot.all(conf)) * 2  # DIR_A and DIR_B
    return {
        'groups': num_groups,
        'slots': num_slots,
        'free_slots': num_slots - num_groups,
        'load': float(num_groups) / num_slots
    }
Exemplo n.º 3
0
def update_group(mailer, id, data):
    """
    Updates an existing group.
    """
    registration_open = Setting.get('registration_open', False)

    group = Group.one(id=id)
    group.name = data['name']
    group.phone = data['phone']
    group.comments = data['comments']
    group.contact = data['contact']
    group.email = data['email']

    # Only allow the number of participants to change as long as the
    # registration is open!
    if data['user_is_admin'] or registration_open:
        group.num_vegetarians = data['num_vegetarians']
        group.num_participants = data['num_participants']

    if 'direction' in data:
        group.direction = data['direction']

    if 'start_time' in data:
        group.start_time = data['start_time']

    if 'cancelled' in data:
        group.cancelled = data['cancelled']

    if 'completed' in data:
        group.completed = data['completed']

    send_email = data.get('send_email', True)
    if data['notification_recipient'] == 'admins':
        admin_query = Role.query.filter(Role.name == Role.ADMIN)
        if admin_query.count():
            recipients = [(user.email, user.name)
                          for user in admin_query[0].user]
        else:
            recipients = []
    elif data['notification_recipient'] == 'owner':
        recipients = [(group.user.email, data['contact'])]
    else:
        LOG.warning('Got an unexpected mail recipient hint: %r',
                    data['notification_recipient'])

    if send_email and recipients:
        mailer.send('registration_update',
                    to=recipients,
                    data={
                        'group': group
                    })
    else:
        LOG.debug('No mail sent: vars=%r', locals())
Exemplo n.º 4
0
def _generate_state_list(station):
    """
    Generates a simple Python dictionary with current group "states".
    """
    if not station:
        return []
    groups = Group.all().order_by(Group.order)
    state_info = DB.session.query(GroupStation).filter(
        GroupStation.station == station)
    state_info_map = {state.group: state for state in state_info}
    output = []
    for group in groups:
        si = state_info_map.get(group)
        output.append({
            "stationId": si.station_id if si else 0,
            "groupId": group.id,
            "groupName": group.name,
            "formScore": (si.form_score or 0) if si else 0,
            "stationScore": (si.score or 0) if si else 0,
            "state": si.state if si else 0
        })
    output = sorted(output, key=lambda x: (x['state'], x['groupName']))
    return output
Exemplo n.º 5
0
def store_registration(session, data, url, needs_confirmation=True):
    """
    Stores a registration to the database.

    The *data* dictionary contains the following items (all strings):

        * group_name
        * contact_name
        * email
        * tel
        * time
        * comments

    If *needs_confirmation* is true (the default), this method will store the
    reservation as "not yet confirmed". An e-mail will be sent out to the
    address specified in the *email* field. The e-mail will contain a link to
    ``/confirm/<key>`` where ``<key`` is a randomly generated string.

    @franky: implement
    @franky: urllib.quote_plus(os.urandom(50).encode('base64')[0:30])
    @franky: See ``_external`` at
             http://flask.pocoo.org/docs/api/#flask.url_for
    @franky: The "key" should be unique in the DB. Generate new keys as long as
             duplicates are found in the DB.
    mailing with python: https://pypi.python.org/pypi/Envelopes/0.4
    """
    qry = Group.query.filter_by(name=data['group_name'])
    check = qry.first()
    if check:
        raise ValueError('Group {} already registered'.format(
            data['group_name']))
    else:
        key = os.urandom(50).encode('base64').replace('/', '')[0:20]
        qry = Group.query.filter_by(confirmation_key=key)
        check_key = qry.first()
        while check_key:
            key = os.urandom(50).encode('base64').replace('/', '')[0:20]
            qry = Group.query.filter_by(confirmation_key=key)
            check_key = qry.first()

        new_grp = Group(data['group_name'],
                        data['contact_name'],
                        data['tel'],
                        None,
                        data['time'],
                        data['email'],
                        data['comments'],
                        key
                        )
        new_grp.order = start_time_to_order(data['time'])

        session.add(new_grp)
        try:
            session.flush()
        except IntegrityError:
            session.rollback()
            LOG.exception('Error while adding the new group {0}'.format(
                data['group_name']))
            raise ValueError('Error while adding the new group {0}'.format(
                data['group_name']))

        if needs_confirmation:
            confirm_link = '{}/{}'.format(url, urllib.quote_plus(key))
            send('confirm',
                 to=(data['email'], data['contact_name']),
                 data={
                     'confirmation_link': confirm_link
                 })
        return True