Example #1
0
def all_user_tickets(context, uid=None, conference=None, status="complete", fare_type="conference"):
    if uid is None:
        uid = context['request'].user.id
    if conference is None:
        conference = settings.CONFERENCE_CONFERENCE
    tickets = dataaccess.all_user_tickets(uid, conference)
    if status == 'complete':
        tickets = filter(lambda x: x[3], tickets)
    elif status == 'incomplete':
        tickets = filter(lambda x: not x[3], tickets)
    if fare_type != "all":
        tickets = filter(lambda x: x[1] == fare_type, tickets)
    return tickets
Example #2
0
def all_user_tickets(context, uid=None, conference=None, status="complete", fare_type="conference"):
    if uid is None:
        uid = context['request'].user.id
    if conference is None:
        conference = settings.CONFERENCE_CONFERENCE
    tickets = dataaccess.all_user_tickets(uid, conference)
    if status == 'complete':
        tickets = filter(lambda x: x[3], tickets)
    elif status == 'incomplete':
        tickets = filter(lambda x: not x[3], tickets)
    if fare_type != "all":
        tickets = filter(lambda x: x[1] == fare_type, tickets)
    return tickets
Example #3
0
    def send_user_message(self, from_, subject, message):
        from conference.models import Conference, AttendeeLink
        if not self.spam_user_message:
            # If there's a link between the two users the message is allowed
            # despite spam_user_message
            try:
                AttendeeLink.objects.getLink(from_.id, self.profile_id)
            except AttendeeLink.DoesNotExist:
                raise ValueError(
                    "This user does not want to receive a message")
        if not from_.email:
            raise ValueError("Sender without an email address")
        if not self.profile.user.email:
            raise ValueError("Recipient without an email address")

        from p3.dataaccess import all_user_tickets
        conf = Conference.objects.current()

        tickets = [
            tid for tid, ftype, _, complete in all_user_tickets(
                from_.id, conf.code) if ftype == 'conference' and complete
        ]
        if not tickets:
            raise ValueError("User without a valid ticket")

        if not conf.conference_end or datetime.date.today(
        ) > conf.conference_end:
            raise ValueError("conference %s is ended" % conf.code)

        from django.core.mail import EmailMessage
        EmailMessage(subject=subject,
                     body=message + dsettings.P3_USER_MESSAGE_FOOTER,
                     from_email=from_.email,
                     to=[self.profile.user.email],
                     headers={
                         'Sender': '*****@*****.**',
                     }).send()
        log.info('email from "%s" to "%s" sent', from_.email,
                 self.profile.user.email)
Example #4
0
    def clean_value(self):
        data = super(P3EventBookingForm, self).clean_value()
        if not data:
            return data
        # A "standard" or "daily" ticket is required to book a training
        tt = cmodels.Event.objects\
            .filter(id=self.event)\
            .values('talk__type')[0]['talk__type']
        tickets = dataaccess.all_user_tickets(
            self.user, conference=settings.CONFERENCE_CONFERENCE)
        for tid, ttype, fcode, complete in tickets:
            if complete and ttype == 'conference'\
                and (fcode[2] in ('S', 'D') or tt != 't'):
                break
        else:
            raise forms.ValidationError('ticket error')

        # No more than one helpdesk per type can be booked
        helpdesk = None
        for t in cmodels.EventTrack.objects\
                    .filter(event=self.event)\
                    .values('track', 'track__track'):
            if 'helpdesk' in t['track__track']:
                helpdesk = t['track']
                break
        if helpdesk:
            custom = cmodels.Event.objects\
                .filter(id=self.event)\
                .values_list('custom', flat=True)[0]
            brothers = cmodels.EventTrack.objects\
                .exclude(event=self.event)\
                .filter(track=helpdesk, event__custom=custom)\
                .values('event')
            booked = cmodels.EventBooking.objects\
                .filter(event__in=brothers, user=self.user)
            if booked.count() > 0:
                raise forms.ValidationError(_('already booked'))
        return data
Example #5
0
    def send_user_message(self, from_, subject, message):
        from conference.models import Conference, AttendeeLink
        if not self.spam_user_message:
            # If there's a link between the two users the message is allowed
            # despite spam_user_message
            try:
                AttendeeLink.objects.getLink(from_.id, self.profile_id)
            except AttendeeLink.DoesNotExist:
                raise ValueError("This user does not want to receive a message")
        if not from_.email:
            raise ValueError("Sender without an email address")
        if not self.profile.user.email:
            raise ValueError("Recipient without an email address")

        from p3.dataaccess import all_user_tickets
        conf = Conference.objects.current()

        tickets = [
            tid
            for tid, ftype, _, complete in all_user_tickets(from_.id, conf.code)
            if ftype == 'conference' and complete
        ]
        if not tickets:
            raise ValueError("User without a valid ticket")

        if not conf.conference_end  or datetime.date.today() > conf.conference_end:
            raise ValueError("conference %s is ended" % conf.code)

        from django.core.mail import EmailMessage
        EmailMessage(
            subject=subject, body=message + dsettings.P3_USER_MESSAGE_FOOTER,
            from_email=from_.email,
            to=[self.profile.user.email],
            headers={
                'Sender': '*****@*****.**',
            }
        ).send()
        log.info('email from "%s" to "%s" sent', from_.email, self.profile.user.email)
Example #6
0
    def clean_value(self):
        data = super(P3EventBookingForm, self).clean_value()
        if not data:
            return data
        # per prenotare un training è necessario un biglietto "standard" o "daily"
        tt = cmodels.Event.objects\
            .filter(id=self.event)\
            .values('talk__type')[0]['talk__type']
        tickets = dataaccess.all_user_tickets(
            self.user, conference=settings.CONFERENCE_CONFERENCE)
        for tid, ttype, fcode, complete in tickets:
            if complete and ttype == 'conference'\
                and (fcode[2] in ('S', 'D') or tt != 't'):
                break
        else:
            raise forms.ValidationError('ticket error')

        # non posso prenotare piŭ di un helpdesk dello stesso tipo
        helpdesk = None
        for t in cmodels.EventTrack.objects\
                    .filter(event=self.event)\
                    .values('track', 'track__track'):
            if 'helpdesk' in t['track__track']:
                helpdesk = t['track']
                break
        if helpdesk:
            custom = cmodels.Event.objects\
                .filter(id=self.event)\
                .values_list('custom', flat=True)[0]
            brothers = cmodels.EventTrack.objects\
                .exclude(event=self.event)\
                .filter(track=helpdesk, event__custom=custom)\
                .values('event')
            booked = cmodels.EventBooking.objects\
                .filter(event__in=brothers, user=self.user)
            if booked.count() > 0:
                raise forms.ValidationError('already booked')
        return data
Example #7
0
    def clean_value(self):
        data = super(P3EventBookingForm, self).clean_value()
        if not data:
            return data
        # A "standard" or "daily" ticket is required to book a training
        tt = cmodels.Event.objects\
            .filter(id=self.event)\
            .values('talk__type')[0]['talk__type']
        tickets = dataaccess.all_user_tickets(self.user, conference=settings.CONFERENCE_CONFERENCE)
        for tid, ttype, fcode, complete in tickets:
            if complete and ttype == 'conference'\
                and (fcode[2] in ('S', 'D') or tt != 't'):
                break
        else:
            raise forms.ValidationError('ticket error')

        # No more than one helpdesk per type can be booked
        helpdesk = None
        for t in cmodels.EventTrack.objects\
                    .filter(event=self.event)\
                    .values('track', 'track__track'):
            if 'helpdesk' in t['track__track']:
                helpdesk = t['track']
                break
        if helpdesk:
            custom = cmodels.Event.objects\
                .filter(id=self.event)\
                .values_list('custom', flat=True)[0]
            brothers = cmodels.EventTrack.objects\
                .exclude(event=self.event)\
                .filter(track=helpdesk, event__custom=custom)\
                .values('event')
            booked = cmodels.EventBooking.objects\
                .filter(event__in=brothers, user=self.user)
            if booked.count() > 0:
                raise forms.ValidationError(_('already booked'))
        return data
Example #8
0
    def clean_value(self):
        data = super(P3EventBookingForm, self).clean_value()
        if not data:
            return data
        # per prenotare un training è necessario un biglietto "standard" o "daily"
        tt = cmodels.Event.objects\
            .filter(id=self.event)\
            .values('talk__type')[0]['talk__type']
        tickets = dataaccess.all_user_tickets(self.user, conference=settings.CONFERENCE_CONFERENCE)
        for tid, ttype, fcode, complete in tickets:
            if complete and ttype == 'conference'\
                and (fcode[2] in ('S', 'D') or tt != 't'):
                break
        else:
            raise forms.ValidationError('ticket error')

        # non posso prenotare piŭ di un helpdesk dello stesso tipo
        helpdesk = None
        for t in cmodels.EventTrack.objects\
                    .filter(event=self.event)\
                    .values('track', 'track__track'):
            if 'helpdesk' in t['track__track']:
                helpdesk = t['track']
                break
        if helpdesk:
            custom = cmodels.Event.objects\
                .filter(id=self.event)\
                .values_list('custom', flat=True)[0]
            brothers = cmodels.EventTrack.objects\
                .exclude(event=self.event)\
                .filter(track=helpdesk, event__custom=custom)\
                .values('event')
            booked = cmodels.EventBooking.objects\
                .filter(event__in=brothers, user=self.user)
            if booked.count() > 0:
                raise forms.ValidationError('already booked')
        return data
Example #9
0
def conference_speakers_day(conf, code=None):
    from p3 import dataaccess
    from conference.dataaccess import talks_data
    from conference.dataaccess import events

    schedules = cmodels.Schedule.objects.filter(conference=conf)
    data = {}
    for s in schedules:
        people = dataaccess.profiles_data(s.speakers()\
            .order_by('user__first_name', 'user__last_name')\
            .values_list('user', flat=True))
        people_data = []
        for p in people:
            o = {
                'uid': p['id'],
                'email': p['email'],
                'name': p['name'],
                'phones': [p['phone']],
                'talks': p['talks']['accepted'].get(conf, []),
            }
            people_data.append(o)
        data[s.date.strftime('%Y-%m-%d')] = people_data
    if code is None:
        output = []
        for date, peoples in sorted(data.items()):
            output.append({
                'id': 'd%s' % date,
                'title': date,
                'total': len(peoples),
            })
        return output
    else:
        people_data = data[code[1:]]
        conf_events = dict([(x['id'], x) for x in events(conf=conf)])
        tracks = defaultdict(list)
        for p in people_data:
            tickets = [
                tid for tid, _, fare, complete in dataaccess.all_user_tickets(
                    p['uid'], conf) if complete and fare.startswith('SIM')
            ]
            if tickets:
                p['phones'].extend(
                    models.TicketSIM.objects\
                        .filter(ticket__in=tickets)\
                        .values_list('number', flat=True))
            p['phones'] = filter(None, p['phones'])
            for talk in talks_data(p['talks']):
                for event_id in talk['events_id']:
                    if conf_events[event_id]['time'].date().strftime(
                            '%Y-%m-%d') == code[1:]:
                        for track in conf_events[event_id]['tracks']:
                            if p not in tracks[track]:
                                tracks[track].append(p)
        output = {
            'columns': (
                ('name', 'Name'),
                ('email', 'Email'),
                ('phones', 'Phones'),
                ('track', 'Track'),
            ),
            'data': [],
        }
        data = output['data']
        for track, people in sorted(tracks.items()):
            for x in people:
                data.append({
                    'name':
                    '<a href="%s">%s</a>' %
                    (reverse('admin:auth_user_change',
                             args=(x['uid'], )), x['name']),
                    'email':
                    x['email'],
                    'uid':
                    x['uid'],
                    'phones':
                    ', '.join(x['phones']),
                    'track':
                    track,
                })
        return output
Example #10
0
def whos_coming(request, conference=None):
    if conference is None:
        return redirect('p3-whos-coming-conference', conference=settings.CONFERENCE_CONFERENCE)
    # i profili possono essere o pubblici o accessibili solo ai partecipanti,
    # nel secondo caso li possono vedere solo chi ha un biglietto.
    access = ('p',)
    if request.user.is_authenticated():
        t = dataaccess.all_user_tickets(request.user.id, conference)
        if any(tid for tid, _, _, complete in t if complete):
            access = ('m', 'p')

    countries = [('', 'All')] + list(amodels.Country.objects\
        .filter(iso__in=models.P3Profile.objects\
            .filter(profile__visibility__in=access)\
            .exclude(country='')\
            .values('country')
        )\
        .values_list('iso', 'name')\
        .distinct()
    )

    class FormWhosFilter(forms.Form):
        country = forms.ChoiceField(choices=countries, required=False)
        speaker = forms.BooleanField(label="Only speakers", required=False)
        tags = cforms.TagField(
            required=False,
            widget=cforms.ReadonlyTagWidget(),
        )

    qs = cmodels.AttendeeProfile.objects\
        .filter(visibility__in=('m', 'p'))\
        .filter(user__in=dataaccess.conference_users(conference))\
        .values('visibility')\
        .annotate(total=Count('visibility'))
    profiles = {
        'all': sum([ row['total'] for row in qs ]),
        'visible': 0,
    }
    for row in qs:
        if row['visibility'] in access:
            profiles['visible'] += row['total']

    people = cmodels.AttendeeProfile.objects\
        .filter(visibility__in=access)\
        .filter(user__in=dataaccess.conference_users(conference))\
        .values_list('user', flat=True)\
        .order_by('user__first_name', 'user__last_name')

    form = FormWhosFilter(data=request.GET)
    if form.is_valid():
        data = form.cleaned_data
        if data.get('country'):
            people = people.filter(p3_profile__country=data['country'])
        if data.get('tags'):
            qs = cmodels.ConferenceTaggedItem.objects\
                .filter(
                    content_type__app_label='p3', content_type__model='p3profile',
                    tag__name__in=data['tags'])\
                .values('object_id')
            people = people.filter(user__in=qs)
        if data.get('speaker'):
            speakers = cmodels.TalkSpeaker.objects\
                .filter(talk__conference=conference, talk__status='accepted')\
                .values('speaker')
            people = people.filter(user__speaker__in=speakers)

    try:
        ix = max(int(request.GET.get('counter', 0)), 0)
    except:
        ix = 0
    pids = people[ix:ix+10]
    ctx = {
        'profiles': profiles,
        'pids': pids,
        'form': form,
        'conference': conference,
    }
    if request.is_ajax():
        tpl = 'p3/ajax/whos_coming.html'
    else:
        tpl = 'p3/whos_coming.html'
    return render(request, tpl, ctx)
Example #11
0
def whos_coming(request, conference=None):
    if conference is None:
        return redirect('p3-whos-coming-conference',
                        conference=settings.CONFERENCE_CONFERENCE)
    # profiles can be public or only visible for participants, in the second
    # case only who has a ticket can see them
    access = ('p', )
    if request.user.is_authenticated():
        t = dataaccess.all_user_tickets(request.user.id, conference)
        if any(tid for tid, _, _, complete in t if complete):
            access = ('m', 'p')

    countries = [('', 'All')] + list(amodels.Country.objects\
        .filter(iso__in=models.P3Profile.objects\
            .filter(profile__visibility__in=access)\
            .exclude(country='')\
            .values('country')
        )\
        .values_list('iso', 'name')\
        .distinct()
    )

    class FormWhosFilter(forms.Form):
        country = forms.ChoiceField(choices=countries, required=False)
        speaker = forms.BooleanField(label="Only speakers", required=False)
        tags = cforms.TagField(
            required=False,
            widget=cforms.ReadonlyTagWidget(),
        )

    qs = cmodels.AttendeeProfile.objects\
        .filter(visibility__in=('m', 'p'))\
        .filter(user__in=dataaccess.conference_users(conference))\
        .values('visibility')\
        .annotate(total=Count('visibility'))
    profiles = {
        'all': sum([row['total'] for row in qs]),
        'visible': 0,
    }
    for row in qs:
        if row['visibility'] in access:
            profiles['visible'] += row['total']

    people = cmodels.AttendeeProfile.objects\
        .filter(visibility__in=access)\
        .filter(user__in=dataaccess.conference_users(conference))\
        .values_list('user', flat=True)\
        .order_by('user__first_name', 'user__last_name')

    form = FormWhosFilter(data=request.GET)
    if form.is_valid():
        data = form.cleaned_data
        if data.get('country'):
            people = people.filter(p3_profile__country=data['country'])
        if data.get('tags'):
            qs = cmodels.ConferenceTaggedItem.objects\
                .filter(
                    content_type__app_label='p3', content_type__model='p3profile',
                    tag__name__in=data['tags'])\
                .values('object_id')
            people = people.filter(user__in=qs)
        if data.get('speaker'):
            speakers = cmodels.TalkSpeaker.objects\
                .filter(talk__conference=conference, talk__status='accepted')\
                .values('speaker')
            people = people.filter(user__speaker__in=speakers)

    try:
        ix = max(int(request.GET.get('counter', 0)), 0)
    except:
        ix = 0
    pids = people[ix:ix + 10]
    ctx = {
        'profiles': profiles,
        'pids': pids,
        'form': form,
        'conference': conference,
    }
    if request.is_ajax():
        tpl = 'p3/ajax/whos_coming.html'
    else:
        tpl = 'p3/whos_coming.html'
    return render(request, tpl, ctx)
Example #12
0
def conference_speakers_day(conf, code=None):
    from p3 import dataaccess
    from conference.dataaccess import talks_data
    from conference.dataaccess import events

    schedules = cmodels.Schedule.objects.filter(conference=conf)
    data = {}
    for s in schedules:
        people = dataaccess.profiles_data(s.speakers()\
            .order_by('user__first_name', 'user__last_name')\
            .values_list('user', flat=True))
        people_data = []
        for p in people:
            o = {
                'uid': p['id'],
                'email': p['email'],
                'name': p['name'],
                'phones': [p['phone']],
                'talks': p['talks']['accepted'].get(conf, []),
            }
            people_data.append(o)
        data[s.date.strftime('%Y-%m-%d')] = people_data
    if code is None:
        output = []
        for date, peoples in sorted(data.items()):
            output.append({
                'id': 'd%s' % date,
                'title': date,
                'total': len(peoples),
            })
        return output
    else:
        people_data = data[code[1:]]
        conf_events = dict([(x['id'], x) for x in events(conf='ep2013')])
        tracks = defaultdict(list)
        for p in people_data:
            tickets = [
                tid for tid, _, fare, complete in dataaccess.all_user_tickets(p['uid'], conf)
                if complete and fare.startswith('SIM') ]
            if tickets:
                p['phones'].extend(
                    models.TicketSIM.objects\
                        .filter(ticket__in=tickets)\
                        .values_list('number', flat=True))
            p['phones'] = filter(None, p['phones'])
            for talk in talks_data(p['talks']):
                for event_id in talk['events_id']:
                    if conf_events[event_id]['time'].date().strftime('%Y-%m-%d') == code[1:]:
                        for track in conf_events[event_id]['tracks']:
                            if p not in tracks[track]:
                                tracks[track].append(p)
        output = {
            'columns': (
                ('name', 'Name'),
                ('email', 'Email'),
                ('phones', 'Phones'),
                ('track', 'Track'),
            ),
            'data': [],
        }
        data = output['data']
        for track, people in sorted(tracks.items()):
            for x in people:
                data.append({
                    'name': '<a href="%s">%s</a>' % (
                        reverse('admin:auth_user_change', args=(x['uid'],)),
                        x['name']),
                    'email': x['email'],
                    'uid': x['uid'],
                    'phones': ', '.join(x['phones']),
                    'track': track,
                })
        return output
Example #13
0
def conference_speakers_day(conf, code=None):
    from p3 import dataaccess
    from conference.dataaccess import talks_data
    from conference.dataaccess import events

    schedules = cmodels.Schedule.objects.filter(conference=conf)
    data = {}
    for s in schedules:
        people = dataaccess.profiles_data(
            s.speakers().order_by("user__first_name", "user__last_name").values_list("user", flat=True)
        )
        people_data = []
        for p in people:
            o = {
                "uid": p["id"],
                "email": p["email"],
                "name": p["name"],
                "phones": [p["phone"]],
                "talks": p["talks"]["accepted"].get(conf, []),
            }
            people_data.append(o)
        data[s.date.strftime("%Y-%m-%d")] = people_data
    if code is None:
        output = []
        for date, peoples in sorted(data.items()):
            output.append({"id": "d%s" % date, "title": date, "total": len(peoples)})
        return output
    else:
        people_data = data[code[1:]]
        conf_events = dict([(x["id"], x) for x in events(conf=conf)])
        tracks = defaultdict(list)
        for p in people_data:
            tickets = [
                tid
                for tid, _, fare, complete in dataaccess.all_user_tickets(p["uid"], conf)
                if complete and fare.startswith("SIM")
            ]
            if tickets:
                p["phones"].extend(models.TicketSIM.objects.filter(ticket__in=tickets).values_list("number", flat=True))
            p["phones"] = filter(None, p["phones"])
            for talk in talks_data(p["talks"]):
                for event_id in talk["events_id"]:
                    if conf_events[event_id]["time"].date().strftime("%Y-%m-%d") == code[1:]:
                        for track in conf_events[event_id]["tracks"]:
                            if p not in tracks[track]:
                                tracks[track].append(p)
        output = {
            "columns": (("name", "Name"), ("email", "Email"), ("phones", "Phones"), ("track", "Track")),
            "data": [],
        }
        data = output["data"]
        for track, people in sorted(tracks.items()):
            for x in people:
                data.append(
                    {
                        "name": '<a href="%s">%s</a>'
                        % (reverse("admin:auth_user_change", args=(x["uid"],)), x["name"]),
                        "email": x["email"],
                        "uid": x["uid"],
                        "phones": ", ".join(x["phones"]),
                        "track": track,
                    }
                )
        return output