Exemplo n.º 1
0
def filter_signup():
    """Filter out signups"""
    from operator import __le__, __eq__, __ge__, __lt__, __gt__
    try:
        form = FilterSignupForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate():
            n = int(request.form['n'])
            op = {
                '<': __lt__,
                '<=': __le__,
                '=': __eq__,
                '>=': __ge__,
                '>': __gt__
            }[request.form['operator']]
            for signup in Signup.query.filter_by(
                is_active=True,
                event_id=g.event.id,
                category=request.form['category']):
                if op(getattr(signup.user, request.form['value']), n):
                        signup.update(is_active=False).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
            title='Remove Signups by Filter',
            form=form,
            message='Use the following to filter out signups. Signups that MATCH this filter will be removed.',
            submit='Remove')
    except NoResultFound:
        abort(404)
Exemplo n.º 2
0
def distribute():
    """categorize users"""

    # TODO: provide less hacky fix
    class CategorizeHackForm(CategorizeBatchForm):
        pass
    for category, count in g.event.category_defaults:
        setattr(CategorizeHackForm, category, wtf.IntegerField(category,
            description='Number of signups to allocate to %s' % category,
            default=count))

    try:
        form = CategorizeHackForm(request.form)
        form.category.choices = choicify(['*'] + g.event.categories)
        if request.method == 'POST' and form.validate():
            signups = iter(g.event.signups_by_category(
                category=request.form['category']))
            for category in g.event.categories:
                count = int(request.form[category])
                for _ in range(count):
                    signup = next(signups)
                    signup.update(category=category).save()
            return redirect(url_for('event.home'))
        form.category.description = 'Category to pull signups from and distribute among the categories in specified amounts.'
        return render_event('event/form.html',
            title='Distribute Signups',
            form=form,
            submit='Distribute')
    except StopIteration:
        pass
    return redirect(url_for('event.home'))
Exemplo n.º 3
0
def filter_signup():
    """Filter out signups"""
    from operator import __le__, __eq__, __ge__, __lt__, __gt__
    try:
        form = FilterSignupForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate():
            n = int(request.form['n'])
            op = {
                '<': __lt__,
                '<=': __le__,
                '=': __eq__,
                '>=': __ge__,
                '>': __gt__
            }[request.form['operator']]
            for signup in Signup.query.filter_by(
                    is_active=True,
                    event_id=g.event.id,
                    category=request.form['category']):
                if op(getattr(signup.user, request.form['value']), n):
                    signup.update(is_active=False).save()
            return redirect(url_for('event.home'))
        return render_event(
            'event/form.html',
            title='Remove Signups by Filter',
            form=form,
            message=
            'Use the following to filter out signups. Signups that MATCH this filter will be removed.',
            submit='Remove')
    except NoResultFound:
        abort(404)
Exemplo n.º 4
0
def distribute():
    """categorize users"""

    # TODO: provide less hacky fix
    class CategorizeHackForm(CategorizeBatchForm):
        pass

    for category, count in g.event.category_defaults:
        setattr(
            CategorizeHackForm, category,
            wtf.IntegerField(
                category,
                description='Number of signups to allocate to %s' % category,
                default=count))

    try:
        form = CategorizeHackForm(request.form)
        form.category.choices = choicify(['*'] + g.event.categories)
        if request.method == 'POST' and form.validate():
            signups = iter(
                g.event.signups_by_category(category=request.form['category']))
            for category in g.event.categories:
                count = int(request.form[category])
                for _ in range(count):
                    signup = next(signups)
                    signup.update(category=category).save()
            return redirect(url_for('event.home'))
        form.category.description = 'Category to pull signups from and distribute among the categories in specified amounts.'
        return render_event('event/form.html',
                            title='Distribute Signups',
                            form=form,
                            submit='Distribute')
    except StopIteration:
        pass
    return redirect(url_for('event.home'))
Exemplo n.º 5
0
class GroupForm(ModelForm):
    """form for groups"""
    class Meta:
        model = Group
        only = ('name', 'description', 'url')

    category = wtf.SelectField('Category',
                               choices=choicify(default_group_roles.keys()),
                               coerce=str)
Exemplo n.º 6
0
class FilterSignupForm(wtf.Form):
    """filter out signups"""

    value = wtf.SelectField(choices=[
        ('num_active_signups', 'User\'s Number of Active Signups'),
        ('num_waitlisted_signups', 'User\'s Number of Waitlisted Signups'),
        ('num_non_waitlisted_signups', 'User\'s Number of Non-Waitlisted Signups')
    ])
    operator = wtf.SelectField(choices=choicify(['<', '<=', '=', '>=', '>']))
    n = wtf.IntegerField('n', description='number')
    category = wtf.SelectField('Category', description='Select a category of signups to apply this filter to.')
Exemplo n.º 7
0
class EventForm(ModelForm):
    """form for user events"""

    name = wtf.StringField('Name')
    description = wtf.StringField('Description', description='(optional)')
    start = wtf.DateTimeField(description='2016-01-13 12:00:00')
    end = wtf.DateTimeField(description='2016-01-13 12:00:00')
    group_id = wtf.HiddenField('group_id')
    days_of_the_week = MultiCheckboxField(
        'Days of the Week',
        choices=choicify(Event.DAYS_OF_THE_WEEK),
        description='Days of the week that this event repeats on')
    frequency = wtf.IntegerField(
        'Frequency',
        description='Happens every _ weeks')
    until = wtf.DateTimeField(description='2016-01-13 12:00:00')
Exemplo n.º 8
0
def categorize(signup_id='all', category=None):
    """Categorize signup"""
    try:
        form = CategorizeForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate() or category:
            if signup_id == 'all':
                for signup in Signup.query.filter_by(event_id=g.event.id, is_active=True).all():
                    signup.update(category=request.form.get('category', category)).save()
            else:
                Signup.query.get(signup_id).update(category=request.form.get('category', category)).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
            title='Categorize',
            form=form,
            submit='Categorize %s' % (signup.user.name if signup_id != 'all' else 'all'))
    except NoResultFound:
        abort(404)
Exemplo n.º 9
0
def recategorize_signup(signup_id):
    """Deactivate signup"""
    try:
        signup = Signup.query.get(signup_id)
        form = CategorizeForm(request.form)
        add_count = lambda c: c + ' (%d signup)' % Signup.query.filter_by(
            event_id=g.event.id, category=c, is_active=True).count()
        form.category.choices = choicify([add_count(c) for c in
            g.event.categories])
        if request.method == 'POST' and form.validate():
            category = request.form['category'].split('(')[0]
            signup.update(category=category).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
            title='Recategorize Signup',
            form=form,
            message='Assign the signup to a new category',
            submit='Recategorize')
    except NoResultFound:
        abort(404)
Exemplo n.º 10
0
def recategorize_signup(signup_id):
    """Deactivate signup"""
    try:
        signup = Signup.query.get(signup_id)
        form = CategorizeForm(request.form)
        add_count = lambda c: c + ' (%d signup)' % Signup.query.filter_by(
            event_id=g.event.id, category=c, is_active=True).count()
        form.category.choices = choicify(
            [add_count(c) for c in g.event.categories])
        if request.method == 'POST' and form.validate():
            category = request.form['category'].split('(')[0]
            signup.update(category=category).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
                            title='Recategorize Signup',
                            form=form,
                            message='Assign the signup to a new category',
                            submit='Recategorize')
    except NoResultFound:
        abort(404)
Exemplo n.º 11
0
def categorize(signup_id='all', category=None):
    """Categorize signup"""
    try:
        form = CategorizeForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate() or category:
            if signup_id == 'all':
                for signup in Signup.query.filter_by(event_id=g.event.id,
                                                     is_active=True).all():
                    signup.update(category=request.form.get(
                        'category', category)).save()
            else:
                Signup.query.get(signup_id).update(
                    category=request.form.get('category', category)).save()
            return redirect(url_for('event.home'))
        return render_event(
            'event/form.html',
            title='Categorize',
            form=form,
            submit='Categorize %s' %
            (signup.user.name if signup_id != 'all' else 'all'))
    except NoResultFound:
        abort(404)
Exemplo n.º 12
0
def sync(service):
    """sync events with service"""
    try:
        form, message = SyncForm(
            request.form), 'See fields below for instructions.'
        setting = g.group.setting(service)
        calendars = setting.value.split(',') if setting.value else []
        form.calendar.choices = choicify(calendars)
        form.recurrence_start.default = arrow.now().to('local')
        form.recurrence_end.default = arrow.now().to('local').replace(weeks=1)
        if not calendars:
            message = 'You have no %s to select from! Access the <a href="%s#%s">settings</a> window to add %s IDs.' % (
                setting.label, url_for('group.settings'), setting.name,
                setting.label)
            form = None
        if (request.method == 'POST' and form.validate()
                and calendars) or 'confirm' in request.form:

            calendarId = request.form['calendar']

            pattern = request.form.get('pattern', '*')
            if pattern != '*':
                pattern = re.compile(request.form['pattern'])

            # TODO: combine with regular login
            if 'credentials' not in session:
                session['redirect'] = current_url()
                return redirect(url_for('public.login'))
            credentials = client.OAuth2Credentials.from_json(
                session['credentials'])
            if credentials.access_token_expired:
                session['redirect'] = current_url()
                return redirect(url_for('public.login'))
            http_auth = credentials.authorize(httplib2.Http())
            service = discovery.build('calendar', 'v3', http=http_auth)

            all_events = []
            page_token = None
            while True:
                events = service.events().list(calendarId=calendarId.strip(),
                                               pageToken=page_token).execute()
                for event in events['items']:
                    all_events.append(event)
                page_token = events.get('nextPageToken')
                if not page_token:
                    break

            all_events = [
                e for e in all_events
                if (pattern == '*' or pattern.match(e.get('summary', 'None')))
                and 'start' in e
            ]

            # hacky fix for daylight savings below
            events = [
                dict(name=e.get('summary', '')[:50],
                     description=e.get('summary', ''),
                     start=arrow.get(e['start'].get(
                         'dateTime',
                         e['start'].get('date',
                                        None))).to('local').replace(hours=-1),
                     end=arrow.get(e['end'].get('dateTime', e['start'].get(
                         'date', None))).to('local').replace(hours=-1),
                     google_id=e['id'],
                     group_id=g.group.id,
                     recurrence=e.get('recurrence', [])) for e in all_events
            ]

            if 'confirm' not in request.form:
                form = ConfirmSyncForm(request.form)
                message = 'Are you sure? %d events will be synced:<br><br> %s' % (
                    len(all_events), '<br>'.join(
                        '{name} <span class="subtext">({start} to {end})</span>'
                        .format(name=e['name'],
                                start=e['start'].format('MMM D h:mm a'),
                                end=e['end'].format('MMM D h:mm a'))
                        for e in events))
                return render_group('group/form.html',
                                    wide_title=True,
                                    form_title='Confirm Sync',
                                    form_message=message,
                                    submit='Sync',
                                    form=form,
                                    back=url_for('group.events'))

            for event_data in events:

                query = Event.query.filter_by(
                    google_id=event_data['google_id'])
                raw_recurrence = event_data.pop('recurrence')
                if raw_recurrence:
                    recurrence = dict(
                        item.split('=')
                        for item in raw_recurrence[0].split(':')[1].split(';'))
                    event_data.update({
                        'frequency':
                        recurrence.get('FREQ', ''),
                        'until':
                        arrow.get(recurrence.get('UNTIL', ''), 'YYYYMMDD'),
                        # 'byday': recurrence.get('BYDAY', '') # TODO: properly implement byday
                    })

                if not query.count():
                    Event(**event_data).save()
                else:
                    query.first().update(**event_data).save()

            return redirect(url_for('group.events'))
        if form:
            form.process()
        return render_group('group/form.html',
                            wide_title=True,
                            form_title='Sync with %s' % setting.label,
                            form_description=message,
                            submit='Sync',
                            form=form,
                            back=url_for('group.events'))
    except AssertionError:
        abort(404)
    except googleapiclient.errors.HttpError:
        form.errors.setdefault(
            'calendar',
            []).append('Google Calendar failed to load. Wrong link perhaps?')
        return render_group('group/form.html',
                            title='Sync with %s' % setting.label,
                            message=message,
                            submit='Sync',
                            form=form,
                            back=url_for('group.events'))