Beispiel #1
0
def top_consumers(start=None, end=None, simple=False):
    """`start` and `end` are dates. Returns top consumers in the interval with
    order counts annotated (num_orders). If `simple` is true the returned list
    consists of serializable data types only. """
    if start is None:
        start = datetime(1970, 1, 1, 0, 0)
    if end is None:
        end = datetime(2999, 1, 1, 0, 0)

    fmt = '%Y-%m-%d'
    key = 'baljan.stats.start-%s.end-%s' % (start.strftime(fmt), end.strftime(fmt))
    top = cache.get(key)
    if top is None:
        top = User.objects.filter(
            profile__show_profile=True,
            order__put_at__gte=start,
            order__put_at__lte=end,
        ).annotate(
            num_orders=Count('order'),
        ).order_by('-num_orders')

        quarter = 60 * 15 # seconds
        cache.set(key, top, quarter)

    if simple:
        simple_top = []
        for u in top:
            simple_top.append({
                'full_name': display_name(u),
                'username': u.username,
                'blipped': u.num_orders,
            })
        return simple_top
    return top
Beispiel #2
0
def union_info(user):
    union_key = 'liuStudentUnionMembership'
    try:
        unions = ldapbackend.search(user.username)[0][1][union_key]
        unions = [u.decode('utf-8') for u in unions]
    except (IndexError, KeyError):
        unions = []

    unions_str = ", ".join(unions)
    name_str = str(display_name(user).ljust(40))
    groups = [g.name for g in user.groups.all()]
    class_str = "normal"
    if 'styrelsen' in groups:
        class_str = "board"
    elif '_gamlingar' in groups:
        class_str = "oldie"
    elif 'jobbare' in groups:
        class_str = "worker"

    class_str = class_str.ljust(10)

    output = "%(name)s%(class)s%(unions)s" % {
        'name': name_str,
        'unions': unions_str,
        'class': class_str,
    }
    print(output)
Beispiel #3
0
def traderequest_notice_save(tr):
    if tr.answered:
        pass
    else:
        if tr.wanted_signup.shift.when < date.today():
            return
        if tr.offered_signup.shift.when < date.today():
            return

        requestee = tr.wanted_signup.user
        requestor = tr.offered_signup.user
        notifications.send('new_trade_request',
            requestee,
            requestor=display_name(requestor),
            wanted_shift=tr.wanted_signup.shift.name(),
            offered_shift=tr.offered_signup.shift.name(),
        )
Beispiel #4
0
def traderequest_notice_save(tr):
    if tr.answered:
        pass
    else:
        if tr.wanted_signup.shift.when < date.today():
            return
        if tr.offered_signup.shift.when < date.today():
            return

        requestee = tr.wanted_signup.user
        requestor = tr.offered_signup.user
        notifications.send('new_trade_request',
            requestee,
            requestor=display_name(requestor),
            wanted_shift=tr.wanted_signup.shift.name(),
            offered_shift=tr.offered_signup.shift.name(),
        )
Beispiel #5
0
def top_consumers(start=None, end=None, simple=False, location=None):
    """`start` and `end` are dates. Returns top consumers in the interval with
    order counts annotated (num_orders). If `simple` is true the returned list
    consists of serializable data types only. """
    if start is None:
        start = datetime(1970, 1, 1, 0, 0)
    if end is None:
        end = datetime(2999, 1, 1, 0, 0)

    fmt = '%Y-%m-%d'
    key = 'baljan.stats.start-%s.end-%s.location-%s' % (
        start.strftime(fmt), end.strftime(fmt), location)
    top = cache.get(key)
    if top is None:
        filter_args = {
            'profile__show_profile': True,
            'order__put_at__gte': start,
            'order__put_at__lte': end
        }

        if location is not None:
            filter_args['order__location'] = location

        top = User.objects.filter(**filter_args).annotate(
            num_orders=Count('order'), ).order_by('-num_orders')

        quarter = 60 * 15  # seconds
        cache.set(key, top, quarter)

    if simple:
        simple_top = []
        for u in top:
            simple_top.append({
                'full_name': display_name(u),
                'username': u.username,
                'blipped': u.num_orders,
            })
        return simple_top
    return top
Beispiel #6
0
def call_duty_week(request, year=None, week=None):
    user = request.user
    if year is None or week is None:
        year, week = year_and_week()
        plan = planning.BoardWeek.current_week()
    else:
        year = int(year)
        week = int(week)
        plan = planning.BoardWeek(year, week)

    oncall_ids = [[str(oc.id) for oc in sh] for sh in plan.oncall()]
    dom_ids = plan.dom_ids()
    real_ids = dict(list(zip(dom_ids, plan.shift_ids())))
    oncall = dict(list(zip(dom_ids, oncall_ids)))

    avails = plan.available()
    uids = [str(u.id) for u in avails]

    names = [display_name(u) for u in avails]

    initials = all_initials(avails)
    id_initials = dict(list(zip(uids, initials)))

    disp_names = ["%s (%s)" % (name, inits) for name, inits in zip(names, initials)]
    disp_names = [htmlents(dn) for dn in disp_names]
    disp_names = ["&nbsp;".join(dn.split()) for dn in disp_names]

    drag_ids = ['drag-%s' % i for i in initials]
    drags = []
    for drag_id, disp_name in zip(drag_ids, disp_names):
        drags.append('<span id="%s">%s</span>' % (drag_id, disp_name))

    id_drags = dict(list(zip(uids, drags)))

    if request.method == 'POST' and request.is_ajax():
        initial_users = dict(list(zip(initials, avails)))
        for dom_id, shift in zip(dom_ids, plan.shifts):
            old_users = User.objects.filter(oncallduty__shift=shift).distinct()
            new_users = []

            if dom_id in request.POST:
                new_users = [initial_users[x] for x
                        in request.POST[dom_id].split('|')]
            for old_user in old_users:
                if not old_user in new_users:
                    shift.oncallduty_set.filter(user=old_user).delete()
            for new_user in new_users:
                if not new_user in old_users:
                    o, created = models.OnCallDuty.objects.get_or_create(
                        shift=shift,
                        user=new_user
                    )
                    assert created
        messages.add_message(request, messages.SUCCESS,
                _("Your changes were saved."))
        return HttpResponse(json.dumps({'OK':True}))

    adjacent = adjacent_weeks(week_dates(year, week)[0])
    tpl = {}
    tpl['week'] = week
    tpl['year'] = year
    tpl['prev_y'] = adjacent[0][0]
    tpl['prev_w'] = adjacent[0][1]
    tpl['next_y'] = adjacent[1][0]
    tpl['next_w'] = adjacent[1][1]
    tpl['real_ids'] = json.dumps(real_ids)
    tpl['oncall'] = json.dumps(oncall)
    tpl['drags'] = json.dumps(id_drags)
    tpl['initials'] = json.dumps(id_initials)
    tpl['uids'] = json.dumps(uids)
    return render(request, 'baljan/call_duty_week.html', tpl)
Beispiel #7
0
def google_apps_identifier(user, ctx):
    """For Google Apps bulk uploads."""
    email = "*****@*****.**" % (asciilize(display_name(user).lower()).replace(
        ' ', '.'))
    return ','.join([email, user.first_name, user.last_name, random_string(8)])
Beispiel #8
0
def google_apps_identifier(user, ctx):
    """For Google Apps bulk uploads."""
    email = "*****@*****.**" % (asciilize(display_name(user).lower()).replace(' ', '.'))
    return ','.join([email, user.first_name, user.last_name, random_string(8)])
Beispiel #9
0
def call_duty_week(request, year=None, week=None):
    if year is None or week is None:
        year, week = year_and_week()
        plan = planning.BoardWeek.current_week()
    else:
        year = int(year)
        week = int(week)
        plan = planning.BoardWeek(year, week)

    oncall_ids = [[str(oc.id) for oc in sh] for sh in plan.oncall()]
    dom_ids = plan.dom_ids()
    real_ids = dict(list(zip(dom_ids, plan.shift_ids())))
    oncall = dict(list(zip(dom_ids, oncall_ids)))

    avails = plan.available()
    uids = [str(u.id) for u in avails]

    names = [display_name(u) for u in avails]

    initials = all_initials(avails)
    id_initials = dict(list(zip(uids, initials)))

    disp_names = [
        "%s (%s)" % (name, inits) for name, inits in zip(names, initials)
    ]
    disp_names = [htmlents(dn) for dn in disp_names]
    disp_names = ["&nbsp;".join(dn.split()) for dn in disp_names]

    drag_ids = ['drag-%s' % i for i in initials]
    drags = []
    for drag_id, disp_name in zip(drag_ids, disp_names):
        drags.append('<span id="%s">%s</span>' % (drag_id, disp_name))

    id_drags = dict(list(zip(uids, drags)))

    if request.method == 'POST' and request.is_ajax():
        initial_users = dict(list(zip(initials, avails)))
        all_old_users = [User.objects.filter(oncallduty__shift=shift).distinct() \
                    for shift in plan.shifts]

        all_new_users = []
        for dom_id, shift in zip(dom_ids, plan.shifts):
            if dom_id in request.POST:
                all_new_users.append([
                    initial_users[x] for x in request.POST[dom_id].split('|')
                ])
            else:
                all_new_users.append([])

        # Remove old users
        for shift, old_users, new_users in zip(plan.shifts, all_old_users,
                                               all_new_users):
            for old_user in old_users:
                if not old_user in new_users:
                    shift.oncallduty_set.filter(user=old_user).delete()

        # add new users
        for shift, old_users, new_users in zip(plan.shifts, all_old_users,
                                               all_new_users):
            for new_user in new_users:
                if not new_user in old_users:
                    if models.OnCallDuty.objects\
                        .filter(shift__when=shift.when, shift__span=shift.span, user=new_user).exists():
                        messages.add_message(
                            request,
                            messages.ERROR,
                            "Kunde inte lägga till %s %s på pass %s." %
                            (new_user.first_name, new_user.last_name,
                             shift.name_short()),
                            extra_tags="danger")
                    else:
                        o, created = models.OnCallDuty.objects.get_or_create(
                            shift=shift, user=new_user)
                        assert created

        messages.add_message(request, messages.SUCCESS,
                             _("Your changes were saved."))
        return HttpResponse(json.dumps({'OK': True}))

    adjacent = adjacent_weeks(week_dates(year, week)[0])
    tpl = {}
    tpl['week'] = week
    tpl['year'] = year
    tpl['prev_y'] = adjacent[0][0]
    tpl['prev_w'] = adjacent[0][1]
    tpl['next_y'] = adjacent[1][0]
    tpl['next_w'] = adjacent[1][1]
    tpl['real_ids'] = json.dumps(real_ids)
    tpl['oncall'] = json.dumps(oncall)
    tpl['drags'] = json.dumps(id_drags)
    tpl['initials'] = json.dumps(id_initials)
    tpl['uids'] = json.dumps(uids)
    tpl['locations'] = models.Located.LOCATION_CHOICES
    tpl['weekdays'] = list(
        zip(range(1, 6), ['Måndag', 'Tisdag', 'Onsdag', 'Torsdag', 'Fredag']))
    tpl['spans'] = list(range(3))
    return render(request, 'baljan/call_duty_week.html', tpl)