Example #1
0
    def serialize(e):

        dr = e.get_date_range_display()
        if e.has_subevents:
            if e.min_from is None:
                dr = pgettext('subevent', 'No dates')
            else:
                tz = pytz.timezone(e.settings.timezone)
                dr = _('Series:') + ' ' + daterange(
                    e.min_from.astimezone(tz),
                    (e.max_fromto or e.max_to or e.max_from).astimezone(tz))
        return {
            'id':
            e.pk,
            'slug':
            e.slug,
            'organizer':
            str(e.organizer.name),
            'name':
            str(e.name),
            'text':
            str(e.name),
            'date_range':
            dr,
            'url':
            reverse('control:event.index',
                    kwargs={
                        'event': e.slug,
                        'organizer': e.organizer.slug
                    })
        }
Example #2
0
 def get_date_range_display(self, tz=None) -> str:
     """
     Returns a formatted string containing the start date and the end date
     of the event with respect to the current locale and to the ``show_times`` and
     ``show_date_to`` settings.
     """
     tz = tz or self.timezone
     if not self.settings.show_date_to or not self.date_to:
         return _date(self.date_from.astimezone(tz), "DATE_FORMAT")
     return daterange(self.date_from.astimezone(tz), self.date_to.astimezone(tz))
Example #3
0
 def get_context_data(self, **kwargs):
     ctx = super().get_context_data(**kwargs)
     for event in ctx['events']:
         tz = pytz.timezone(event.cache.get_or_set('timezone', lambda: event.settings.timezone))
         if event.has_subevents:
             event.daterange = daterange(
                 event.min_from.astimezone(tz),
                 (event.max_fromto or event.max_to or event.max_from).astimezone(tz)
             )
     return ctx
Example #4
0
 def get_date_range_display(self, tz=None, force_show_end=False) -> str:
     """
     Returns a formatted string containing the start date and the end date
     of the event with respect to the current locale and to the ``show_times`` and
     ``show_date_to`` settings.
     """
     tz = tz or self.timezone
     if (not self.settings.show_date_to and not force_show_end) or not self.date_to:
         return _date(self.date_from.astimezone(tz), "DATE_FORMAT")
     return daterange(self.date_from.astimezone(tz), self.date_to.astimezone(tz))
Example #5
0
 def get_context_data(self, **kwargs):
     ctx = super().get_context_data(**kwargs)
     for event in ctx['events']:
         tz = pytz.timezone(event.cache.get_or_set('timezone', lambda: event.settings.timezone))
         if event.has_subevents:
             event.daterange = daterange(
                 event.min_from.astimezone(tz),
                 (event.max_fromto or event.max_to or event.max_from).astimezone(tz)
             )
     return ctx
Example #6
0
def serialize_event(e):
    dr = e.get_date_range_display()
    if e.has_subevents:
        if e.min_from is None:
            dr = pgettext('subevent', 'No dates')
        else:
            tz = pytz.timezone(e.settings.timezone)
            dr = _('Series:') + ' ' + daterange(
                e.min_from.astimezone(tz),
                (e.max_fromto or e.max_to or e.max_from).astimezone(tz)
            )
    return {
        'id': e.pk,
        'slug': e.slug,
        'type': 'event',
        'organizer': str(e.organizer.name),
        'name': str(e.name),
        'text': str(e.name),
        'date_range': dr,
        'url': reverse('control:event.index', kwargs={
            'event': e.slug,
            'organizer': e.organizer.slug
        })
    }
Example #7
0
def test_same_day_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "Feb. 1st, 2003"
Example #8
0
def test_different_dates_spanish():
    with translation.override('es'):
        df = date(2003, 2, 1)
        dt = date(2005, 4, 3)
        assert daterange(df, dt) == "1 de Febrero de 2003 – 3 de Abril de 2005"
Example #9
0
def test_same_day_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "1. Februar 2003"
Example #10
0
def test_same_year_spanish():
    with translation.override('es'):
        df = date(2003, 2, 1)
        dt = date(2003, 4, 3)
        assert daterange(df, dt) == "1 de Febrero - 3 de Abril de 2003"
Example #11
0
def test_same_year_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2003, 4, 3)
        assert daterange(df, dt) == "1. Februar – 3. April 2003"
Example #12
0
def test_same_day_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "1. Februar 2003"
        assert daterange(df, df, as_html=True) == '<time datetime="2003-02-01">1. Februar 2003</time>'
Example #13
0
 def get_date_range_display(self, tz=None) -> str:
     tz = tz or pytz.timezone(self.settings.timezone)
     if not self.settings.show_date_to or not self.date_to:
         return _date(self.date_from.astimezone(tz), "DATE_FORMAT")
     return daterange(self.date_from.astimezone(tz), self.date_to.astimezone(tz))
Example #14
0
def test_different_dates_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2005, 4, 3)
        assert daterange(df, dt) == "1. Februar 2003 – 3. April 2005"
        assert daterange(df, dt, as_html=True) == '<time datetime="2003-02-01">1. Februar 2003</time> – <time datetime="2005-04-03">3. April 2005</time>'
Example #15
0
def test_same_year_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2003, 4, 3)
        assert daterange(df, dt) == "1. Februar – 3. April 2003"
        assert daterange(df, dt, as_html=True) == '<time datetime="2003-02-01">1. Februar</time> – <time datetime="2003-04-03">3. April 2003</time>'
Example #16
0
def test_same_month_spanish():
    with translation.override('es'):
        df = date(2003, 2, 1)
        dt = date(2003, 2, 3)
        assert daterange(df, dt) == "1 - 3 de Febrero de 2003"
        assert daterange(df, dt, as_html=True) == '<time datetime="2003-02-01">1</time> - <time datetime="2003-02-03">3 de Febrero de 2003</time>'
Example #17
0
def test_same_month_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        dt = date(2003, 2, 3)
        assert daterange(df, dt) == "Feb. 1st – 3rd, 2003"
        assert daterange(df, dt, as_html=True) == '<time datetime="2003-02-01">Feb. 1st</time> – <time datetime="2003-02-03">3rd, 2003</time>'
Example #18
0
def test_same_day_other_lang():
    with translation.override('tr'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == '01 Şubat 2003'
        assert daterange(df, df, as_html=True) == '<time datetime="2003-02-01">01 Şubat 2003</time>'
Example #19
0
def test_same_day_spanish():
    with translation.override('es'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "1 de Febrero de 2003"
        assert daterange(df, df, as_html=True) == '<time datetime="2003-02-01">1 de Febrero de 2003</time>'
Example #20
0
def test_same_day_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "Feb. 1st, 2003"
        assert daterange(df, df, as_html=True) == '<time datetime="2003-02-01">Feb. 1st, 2003</time>'
Example #21
0
def test_same_day_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "1. Februar 2003"
Example #22
0
def test_same_month_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2003, 2, 3)
        assert daterange(df, dt) == "1.–3. Februar 2003"
Example #23
0
def widgets_for_event_qs(request, qs, user, nmax):
    widgets = []

    # Get set of events where we have the permission to show the # of orders
    events_with_orders = set(qs.filter(
        Q(organizer_id__in=user.teams.filter(all_events=True, can_view_orders=True).values_list('organizer', flat=True))
        | Q(id__in=user.teams.filter(can_view_orders=True).values_list('limit_events__id', flat=True))
    ).values_list('id', flat=True))

    tpl = """
        <a href="{url}" class="event">
            <div class="name">{event}</div>
            <div class="daterange">{daterange}</div>
            <div class="times">{times}</div>
        </a>
        <div class="bottomrow">
            {orders}
            <a href="{url}" class="status-{statusclass}">
                {status}
            </a>
        </div>
    """

    events = qs.prefetch_related(
        '_settings_objects', 'organizer___settings_objects'
    ).select_related('organizer')[:nmax]
    for event in events:
        tz = pytz.timezone(event.cache.get_or_set('timezone', lambda: event.settings.timezone))
        if event.has_subevents:
            if event.min_from is None:
                dr = pgettext("subevent", "No dates")
            else:
                dr = daterange(
                    (event.min_from).astimezone(tz),
                    (event.max_fromto or event.max_to or event.max_from).astimezone(tz)
                )
        else:
            if event.date_to:
                dr = daterange(event.date_from.astimezone(tz), event.date_to.astimezone(tz))
            else:
                dr = date_format(event.date_from.astimezone(tz), "DATE_FORMAT")

        if event.has_ra:
            status = ('danger', _('Action required'))
        elif not event.live:
            status = ('warning', _('Shop disabled'))
        elif event.presale_has_ended:
            status = ('default', _('Sale over'))
        elif not event.presale_is_running:
            status = ('default', _('Soon'))
        else:
            status = ('success', _('On sale'))

        widgets.append({
            'content': tpl.format(
                event=escape(event.name),
                times=_('Event series') if event.has_subevents else (
                    ((date_format(event.date_admission.astimezone(tz), 'TIME_FORMAT') + ' / ')
                     if event.date_admission and event.date_admission != event.date_from else '')
                    + (date_format(event.date_from.astimezone(tz), 'TIME_FORMAT') if event.date_from else '')
                ),
                url=reverse('control:event.index', kwargs={
                    'event': event.slug,
                    'organizer': event.organizer.slug
                }),
                orders=(
                    '<a href="{orders_url}" class="orders">{orders_text}</a>'.format(
                        orders_url=reverse('control:event.orders', kwargs={
                            'event': event.slug,
                            'organizer': event.organizer.slug
                        }),
                        orders_text=ungettext('{num} order', '{num} orders', event.order_count or 0).format(
                            num=event.order_count or 0
                        )
                    ) if user.has_active_staff_session(request.session.session_key) or event.pk in events_with_orders else ''
                ),
                daterange=dr,
                status=status[1],
                statusclass=status[0],
            ),
            'display_size': 'small',
            'priority': 100,
            'container_class': 'widget-container widget-container-event',
        })
        """
            {% if not e.live %}
                <span class="label label-danger">{% trans "Shop disabled" %}</span>
            {% elif e.presale_has_ended %}
                <span class="label label-warning">{% trans "Presale over" %}</span>
            {% elif not e.presale_is_running %}
                <span class="label label-warning">{% trans "Presale not started" %}</span>
            {% else %}
                <span class="label label-success">{% trans "On sale" %}</span>
            {% endif %}
        """
    return widgets
Example #24
0
def test_different_dates_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        dt = date(2005, 4, 3)
        assert daterange(df, dt) == "Feb. 1, 2003 – April 3, 2005"
        assert daterange(df, dt, as_html=True) == '<time datetime="2003-02-01">Feb. 1, 2003</time> – <time datetime="2005-04-03">April 3, 2005</time>'
Example #25
0
def test_same_day_spanish():
    with translation.override('es'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "1 de Febrero de 2003"
Example #26
0
def user_event_widgets(**kwargs):
    user = kwargs.pop('user')
    widgets = []

    tpl = """
        <a href="{url}" class="event">
            <div class="name">{event}</div>
            <div class="daterange">{daterange}</div>
            <div class="times">{times}</div>
        </a>
        <div class="bottomrow">
            {orders}
            <a href="{url}" class="status-{statusclass}">
                {status}
            </a>
        </div>
    """

    active_orders = Order.objects.filter(
        event=OuterRef('pk'),
        status__in=[
            Order.STATUS_PENDING, Order.STATUS_PAID
        ]).order_by().values('event').annotate(c=Count('*')).values('c')

    required_actions = RequiredAction.objects.filter(event=OuterRef('pk'),
                                                     done=False)

    # Get set of events where we have the permission to show the # of orders
    events_with_orders = set(
        Event.objects.filter(
            Q(organizer_id__in=user.teams.filter(
                all_events=True, can_view_orders=True).values_list('organizer',
                                                                   flat=True))
            | Q(id__in=user.teams.filter(can_view_orders=True).values_list(
                'limit_events__id', flat=True))).values_list('id', flat=True))

    events = user.get_events_with_any_permission().annotate(
        order_count=Subquery(active_orders, output_field=IntegerField()),
        has_ra=Exists(required_actions)).annotate(
            min_from=Min('subevents__date_from'),
            max_from=Max('subevents__date_from'),
            max_to=Max('subevents__date_to'),
            max_fromto=Greatest(
                Max('subevents__date_to'),
                Max('subevents__date_from'))).annotate(
                    order_from=Coalesce('min_from', 'date_from'),
                    order_to=Coalesce('max_fromto', 'max_to', 'max_from',
                                      'date_to'),
                ).order_by('-order_from', 'name').prefetch_related(
                    '_settings_objects',
                    'organizer___settings_objects').select_related(
                        'organizer')[:100]
    for event in events:
        dr = event.get_date_range_display()
        tz = pytz.timezone(event.settings.timezone)
        if event.has_subevents:
            dr = daterange((event.min_from).astimezone(tz),
                           (event.max_fromto or event.max_to
                            or event.max_from).astimezone(tz))

        if event.has_ra:
            status = ('danger', _('Action required'))
        elif not event.live:
            status = ('warning', _('Shop disabled'))
        elif event.presale_has_ended:
            status = ('default', _('Sale over'))
        elif not event.presale_is_running:
            status = ('default', _('Soon'))
        else:
            status = ('success', _('On sale'))

        widgets.append({
            'content':
            tpl.format(
                event=escape(event.name),
                times=_('Event series') if event.has_subevents else
                (((date_format(event.date_admission.astimezone(tz),
                               'TIME_FORMAT') + ' / ') if event.date_admission
                  and event.date_admission != event.date_from else '') +
                 (date_format(event.date_from.astimezone(tz), 'TIME_FORMAT')
                  if event.date_from else '')),
                url=reverse('control:event.index',
                            kwargs={
                                'event': event.slug,
                                'organizer': event.organizer.slug
                            }),
                orders=(
                    '<a href="{orders_url}" class="orders">{orders_text}</a>'.
                    format(orders_url=reverse('control:event.orders',
                                              kwargs={
                                                  'event': event.slug,
                                                  'organizer':
                                                  event.organizer.slug
                                              }),
                           orders_text=ungettext(
                               '{num} order', '{num} orders', event.order_count
                               or 0).format(num=event.order_count or 0))
                    if user.is_superuser or event.pk in events_with_orders else
                    ''),
                daterange=dr,
                status=status[1],
                statusclass=status[0],
            ),
            'display_size':
            'small',
            'priority':
            100,
            'container_class':
            'widget-container widget-container-event',
        })
        """
            {% if not e.live %}
                <span class="label label-danger">{% trans "Shop disabled" %}</span>
            {% elif e.presale_has_ended %}
                <span class="label label-warning">{% trans "Presale over" %}</span>
            {% elif not e.presale_is_running %}
                <span class="label label-warning">{% trans "Presale not started" %}</span>
            {% else %}
                <span class="label label-success">{% trans "On sale" %}</span>
            {% endif %}
        """
    return widgets
Example #27
0
def test_same_month_spanish():
    with translation.override('es'):
        df = date(2003, 2, 1)
        dt = date(2003, 2, 3)
        assert daterange(df, dt) == "1 - 3 de Febrero de 2003"
Example #28
0
    def _get_event_list(self, request, **kwargs):
        data = {}
        o = getattr(request, 'event', request.organizer)
        list_type = self.request.GET.get("style", o.settings.event_list_type)
        data['list_type'] = list_type

        if hasattr(self.request,
                   'event') and data['list_type'] not in ("calendar", "week"):
            # only allow list-view of more than 50 subevents if ordering is by data as this can be done in the database
            # ordering by name is currently not supported in database due to I18NField-JSON
            ordering = self.request.event.settings.get(
                'frontpage_subevent_ordering',
                default='date_ascending',
                as_type=str)
            if ordering not in ("date_ascending", "date_descending"
                                ) and self.request.event.subevents.filter(
                                    date_from__gt=now()).count() > 50:
                if self.request.event.settings.event_list_type not in (
                        "calendar", "week"):
                    self.request.event.settings.event_list_type = "calendar"
                data['list_type'] = list_type = 'calendar'

        if hasattr(self.request, 'event'):
            data['name'] = str(request.event.name)
            data['frontpage_text'] = str(
                rich_text(request.event.settings.frontpage_text,
                          safelinks=False))

        cache_key = ':'.join([
            'widget.py',
            'eventlist',
            request.organizer.slug,
            request.event.slug if hasattr(request, 'event') else '-',
            list_type,
            request.GET.urlencode(),
            get_language(),
        ])
        cached_data = cache.get(cache_key)
        if cached_data:
            return self.response(cached_data)

        if list_type == "calendar":
            self._set_month_year()
            _, ndays = calendar.monthrange(self.year, self.month)

            data['date'] = date(self.year, self.month, 1)
            if hasattr(self.request, 'event'):
                tz = pytz.timezone(self.request.event.settings.timezone)
            else:
                tz = pytz.UTC
            before = datetime(self.year, self.month, 1, 0, 0, 0,
                              tzinfo=tz) - timedelta(days=1)
            after = datetime(self.year, self.month, ndays, 0, 0, 0,
                             tzinfo=tz) + timedelta(days=1)

            ebd = defaultdict(list)

            if hasattr(self.request, 'event'):
                add_subevents_for_days(
                    filter_qs_by_attr(
                        self.request.event.subevents_annotated('web').filter(
                            event__sales_channels__contains=self.request.
                            sales_channel.identifier), self.request), before,
                    after, ebd, set(), self.request.event,
                    kwargs.get('cart_namespace'))
            else:
                timezones = set()
                add_events_for_days(
                    self.request,
                    filter_qs_by_attr(
                        Event.annotated(
                            self.request.organizer.events,
                            'web').filter(sales_channels__contains=self.
                                          request.sales_channel.identifier),
                        self.request), before, after, ebd, timezones)
                add_subevents_for_days(
                    filter_qs_by_attr(
                        SubEvent.annotated(
                            SubEvent.objects.filter(
                                event__organizer=self.request.organizer,
                                event__is_public=True,
                                event__live=True,
                                event__sales_channels__contains=self.request.
                                sales_channel.identifier).prefetch_related(
                                    'event___settings_objects',
                                    'event__organizer___settings_objects')),
                        self.request), before, after, ebd, timezones)

            data['weeks'] = weeks_for_template(ebd, self.year, self.month)
            for w in data['weeks']:
                for d in w:
                    if not d:
                        continue
                    d['events'] = self._serialize_events(d['events'] or [])
        elif list_type == "week":
            self._set_week_year()

            if hasattr(self.request, 'event'):
                tz = pytz.timezone(self.request.event.settings.timezone)
            else:
                tz = pytz.UTC

            week = isoweek.Week(self.year, self.week)
            data['week'] = [self.year, self.week]
            before = datetime(week.monday().year,
                              week.monday().month,
                              week.monday().day,
                              0,
                              0,
                              0,
                              tzinfo=tz) - timedelta(days=1)
            after = datetime(week.sunday().year,
                             week.sunday().month,
                             week.sunday().day,
                             0,
                             0,
                             0,
                             tzinfo=tz) + timedelta(days=1)

            ebd = defaultdict(list)
            if hasattr(self.request, 'event'):
                add_subevents_for_days(
                    filter_qs_by_attr(
                        self.request.event.subevents_annotated('web'),
                        self.request), before, after, ebd, set(),
                    self.request.event, kwargs.get('cart_namespace'))
            else:
                timezones = set()
                add_events_for_days(
                    self.request,
                    filter_qs_by_attr(
                        Event.annotated(self.request.organizer.events, 'web'),
                        self.request), before, after, ebd, timezones)
                add_subevents_for_days(
                    filter_qs_by_attr(
                        SubEvent.annotated(
                            SubEvent.objects.filter(
                                event__organizer=self.request.organizer,
                                event__is_public=True,
                                event__live=True,
                            ).prefetch_related(
                                'event___settings_objects',
                                'event__organizer___settings_objects')),
                        self.request), before, after, ebd, timezones)

            data['days'] = days_for_template(ebd, week)
            for d in data['days']:
                d['events'] = self._serialize_events(d['events'] or [])
        else:
            offset = int(self.request.GET.get("offset", 0))
            limit = 50
            if hasattr(self.request, 'event'):
                evs = self.request.event.subevents_sorted(
                    filter_qs_by_attr(
                        self.request.event.subevents_annotated(
                            self.request.sales_channel.identifier),
                        self.request))
                ordering = self.request.event.settings.get(
                    'frontpage_subevent_ordering',
                    default='date_ascending',
                    as_type=str)
                data['has_more_events'] = False
                if ordering in ("date_ascending", "date_descending"):
                    # fetch one more result than needed to check if more events exist
                    evs = list(evs[offset:offset + limit + 1])
                    if len(evs) > limit:
                        data['has_more_events'] = True
                        evs = evs[:limit]

                tz = pytz.timezone(request.event.settings.timezone)
                if self.request.event.settings.event_list_available_only:
                    evs = [
                        se for se in evs if not se.presale_has_ended and (
                            se.best_availability_state is not None
                            and se.best_availability_state >=
                            Quota.AVAILABILITY_RESERVED)
                    ]

                data['events'] = [{
                    'name':
                    str(ev.name),
                    'location':
                    str(ev.location),
                    'date_range':
                    self._get_date_range(ev, ev.event, tz),
                    'availability':
                    self._get_availability(ev, ev.event, tz=tz),
                    'event_url':
                    build_absolute_uri(ev.event, 'presale:event.index'),
                    'subevent':
                    ev.pk,
                } for ev in evs]
            else:
                data['events'] = []
                qs = self._get_event_queryset()
                for event in qs:
                    tz = pytz.timezone(
                        event.cache.get_or_set(
                            'timezone', lambda: event.settings.timezone))
                    if event.has_subevents:
                        dr = daterange(event.min_from.astimezone(tz),
                                       (event.max_fromto or event.max_to
                                        or event.max_from).astimezone(tz))
                        avail = {
                            'color': 'none',
                            'text': gettext('Event series')
                        }
                    else:
                        dr = self._get_date_range(event, event, tz)
                        avail = self._get_availability(event, event, tz=tz)
                    data['events'].append({
                        'name':
                        str(event.name),
                        'location':
                        str(event.location),
                        'date_range':
                        dr,
                        'availability':
                        avail,
                        'event_url':
                        build_absolute_uri(event, 'presale:event.index'),
                    })

        cache.set(cache_key, data, 30)
        # These pages are cached for a really short duration – this should make them pretty accurate, while still
        # providing some protection against burst traffic.
        return self.response(data)
Example #29
0
def test_same_year_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        dt = date(2003, 4, 3)
        assert daterange(df, dt) == "Feb. 1st – April 3rd, 2003"
Example #30
0
def test_same_day_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        assert daterange(df, df) == "Feb. 1st, 2003"
Example #31
0
def test_different_dates_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2005, 4, 3)
        assert daterange(df, dt) == "1. Februar 2003 – 3. April 2005"
Example #32
0
def test_same_month_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2003, 2, 3)
        assert daterange(df, dt) == "1.–3. Februar 2003"
Example #33
0
def test_different_dates_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        dt = date(2005, 4, 3)
        assert daterange(df, dt) == "Feb. 1, 2003 – April 3, 2005"
Example #34
0
def test_same_year_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2003, 4, 3)
        assert daterange(df, dt) == "1. Februar – 3. April 2003"
Example #35
0
def widgets_for_event_qs(request, qs, user, nmax):
    widgets = []

    # Get set of events where we have the permission to show the # of orders
    events_with_orders = set(qs.filter(
        Q(organizer_id__in=user.teams.filter(all_events=True, can_view_orders=True).values_list('organizer', flat=True))
        | Q(id__in=user.teams.filter(can_view_orders=True).values_list('limit_events__id', flat=True))
    ).values_list('id', flat=True))

    tpl = """
        <a href="{url}" class="event">
            <div class="name">{event}</div>
            <div class="daterange">{daterange}</div>
            <div class="times">{times}</div>
        </a>
        <div class="bottomrow">
            {orders}
            <a href="{url}" class="status-{statusclass}">
                {status}
            </a>
        </div>
    """

    events = qs.prefetch_related(
        '_settings_objects', 'organizer___settings_objects'
    ).select_related('organizer')[:nmax]
    for event in events:
        tz = pytz.timezone(event.cache.get_or_set('timezone', lambda: event.settings.timezone))
        if event.has_subevents:
            if event.min_from is None:
                dr = pgettext("subevent", "No dates")
            else:
                dr = daterange(
                    (event.min_from).astimezone(tz),
                    (event.max_fromto or event.max_to or event.max_from).astimezone(tz)
                )
        else:
            if event.date_to:
                dr = daterange(event.date_from.astimezone(tz), event.date_to.astimezone(tz))
            else:
                dr = date_format(event.date_from.astimezone(tz), "DATE_FORMAT")

        if event.has_ra:
            status = ('danger', _('Action required'))
        elif not event.live:
            status = ('warning', _('Shop disabled'))
        elif event.presale_has_ended:
            status = ('default', _('Sale over'))
        elif not event.presale_is_running:
            status = ('default', _('Soon'))
        else:
            status = ('success', _('On sale'))

        widgets.append({
            'content': tpl.format(
                event=escape(event.name),
                times=_('Event series') if event.has_subevents else (
                    ((date_format(event.date_admission.astimezone(tz), 'TIME_FORMAT') + ' / ')
                     if event.date_admission and event.date_admission != event.date_from else '')
                    + (date_format(event.date_from.astimezone(tz), 'TIME_FORMAT') if event.date_from else '')
                ),
                url=reverse('control:event.index', kwargs={
                    'event': event.slug,
                    'organizer': event.organizer.slug
                }),
                orders=(
                    '<a href="{orders_url}" class="orders">{orders_text}</a>'.format(
                        orders_url=reverse('control:event.orders', kwargs={
                            'event': event.slug,
                            'organizer': event.organizer.slug
                        }),
                        orders_text=ungettext('{num} order', '{num} orders', event.order_count or 0).format(
                            num=event.order_count or 0
                        )
                    ) if user.has_active_staff_session(request.session.session_key) or event.pk in events_with_orders else ''
                ),
                daterange=dr,
                status=status[1],
                statusclass=status[0],
            ),
            'display_size': 'small',
            'priority': 100,
            'container_class': 'widget-container widget-container-event',
        })
        """
            {% if not e.live %}
                <span class="label label-danger">{% trans "Shop disabled" %}</span>
            {% elif e.presale_has_ended %}
                <span class="label label-warning">{% trans "Presale over" %}</span>
            {% elif not e.presale_is_running %}
                <span class="label label-warning">{% trans "Presale not started" %}</span>
            {% else %}
                <span class="label label-success">{% trans "On sale" %}</span>
            {% endif %}
        """
    return widgets
Example #36
0
def test_same_year_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        dt = date(2003, 4, 3)
        assert daterange(df, dt) == "Feb. 1st – April 3rd, 2003"
Example #37
0
    def _get_event_list(self, request, **kwargs):
        data = {}
        o = getattr(request, 'event', request.organizer)
        list_type = self.request.GET.get("style", o.settings.event_list_type)
        data['list_type'] = list_type

        cache_key = ':'.join([
            'widget.py',
            'eventlist',
            request.organizer.slug,
            request.event.slug if hasattr(request, 'event') else '-',
            list_type,
            request.GET.get("year") or "-",
            request.GET.get("month") or "-",
            request.GET.get("old") or "-",
            get_language(),
        ])
        cached_data = cache.get(cache_key)
        if cached_data:
            return self.response(cached_data)

        if list_type == "calendar":
            self._set_month_year()
            _, ndays = calendar.monthrange(self.year, self.month)

            data['date'] = date(self.year, self.month, 1)
            if hasattr(self.request, 'event'):
                tz = pytz.timezone(self.request.event.settings.timezone)
            else:
                tz = pytz.UTC
            before = datetime(self.year, self.month, 1, 0, 0, 0, tzinfo=tz) - timedelta(days=1)
            after = datetime(self.year, self.month, ndays, 0, 0, 0, tzinfo=tz) + timedelta(days=1)

            ebd = defaultdict(list)

            if hasattr(self.request, 'event'):
                add_subevents_for_days(
                    self.request.event.subevents_annotated('web'),
                    before, after, ebd, set(), self.request.event,
                    kwargs.get('cart_namespace')
                )
            else:
                timezones = set()
                add_events_for_days(self.request, Event.annotated(self.request.organizer.events, 'web'), before, after, ebd, timezones)
                add_subevents_for_days(filter_qs_by_attr(SubEvent.annotated(SubEvent.objects.filter(
                    event__organizer=self.request.organizer,
                    event__is_public=True,
                    event__live=True,
                ).prefetch_related(
                    'event___settings_objects', 'event__organizer___settings_objects'
                )), self.request), before, after, ebd, timezones)

            data['weeks'] = weeks_for_template(ebd, self.year, self.month)
            for w in data['weeks']:
                for d in w:
                    if not d:
                        continue
                    d['events'] = self._serialize_events(d['events'] or [])
        else:
            if hasattr(self.request, 'event'):
                evs = self.request.event.subevents_sorted(
                    self.request.event.subevents_annotated(self.request.sales_channel)
                )
                tz = pytz.timezone(request.event.settings.timezone)
                data['events'] = [
                    {
                        'name': str(ev.name),
                        'date_range': ev.get_date_range_display(tz) + (
                            (" " + ev.get_time_from_display(tz)) if ev.event.settings.show_times else ""
                        ),
                        'availability': self._get_availability(ev, ev.event),
                        'event_url': build_absolute_uri(ev.event, 'presale:event.index'),
                        'subevent': ev.pk,
                    } for ev in evs
                ]
            else:
                data['events'] = []
                qs = self._get_event_queryset()
                for event in qs:
                    tz = pytz.timezone(event.cache.get_or_set('timezone', lambda: event.settings.timezone))
                    if event.has_subevents:
                        dr = daterange(
                            event.min_from.astimezone(tz),
                            (event.max_fromto or event.max_to or event.max_from).astimezone(tz)
                        )
                        avail = {'color': 'none', 'text': ugettext('Event series')}
                    else:
                        dr = event.get_date_range_display(tz) + (
                            " " + event.get_time_from_display(tz) if event.settings.show_times else ""
                        )
                        avail = self._get_availability(event, event)
                    data['events'].append({
                        'name': str(event.name),
                        'date_range': dr,
                        'availability': avail,
                        'event_url': build_absolute_uri(event, 'presale:event.index'),
                    })

        cache.set(cache_key, data, 30)
        # These pages are cached for a really short duration – this should make them pretty accurate, while still
        # providing some protection against burst traffic.
        return self.response(data)
Example #38
0
def test_different_dates_german():
    with translation.override('de'):
        df = date(2003, 2, 1)
        dt = date(2005, 4, 3)
        assert daterange(df, dt) == "1. Februar 2003 – 3. April 2005"
Example #39
0
    def _get_event_list(self, request, **kwargs):
        data = {}
        o = getattr(request, 'event', request.organizer)
        list_type = self.request.GET.get("style", o.settings.event_list_type)
        data['list_type'] = list_type

        if hasattr(self.request,
                   'event') and data['list_type'] not in ("calendar", "week"):
            if self.request.event.subevents.filter(
                    date_from__gt=now()).count() > 50:
                if self.request.event.settings.event_list_type not in (
                        "calendar", "week"):
                    self.request.event.settings.event_list_type = "calendar"
                data['list_type'] = list_type = 'calendar'

        if hasattr(self.request, 'event'):
            data['name'] = str(request.event.name)
            data['frontpage_text'] = str(
                rich_text(request.event.settings.frontpage_text,
                          safelinks=False))

        cache_key = ':'.join([
            'widget.py',
            'eventlist',
            request.organizer.slug,
            request.event.slug if hasattr(request, 'event') else '-',
            list_type,
            request.GET.urlencode(),
            get_language(),
        ])
        cached_data = cache.get(cache_key)
        if cached_data:
            return self.response(cached_data)

        if list_type == "calendar":
            self._set_month_year()
            _, ndays = calendar.monthrange(self.year, self.month)

            data['date'] = date(self.year, self.month, 1)
            if hasattr(self.request, 'event'):
                tz = pytz.timezone(self.request.event.settings.timezone)
            else:
                tz = pytz.UTC
            before = datetime(self.year, self.month, 1, 0, 0, 0,
                              tzinfo=tz) - timedelta(days=1)
            after = datetime(self.year, self.month, ndays, 0, 0, 0,
                             tzinfo=tz) + timedelta(days=1)

            ebd = defaultdict(list)

            if hasattr(self.request, 'event'):
                add_subevents_for_days(
                    filter_qs_by_attr(
                        self.request.event.subevents_annotated('web').filter(
                            event__sales_channels__contains=self.request.
                            sales_channel.identifier), self.request), before,
                    after, ebd, set(), self.request.event,
                    kwargs.get('cart_namespace'))
            else:
                timezones = set()
                add_events_for_days(
                    self.request,
                    filter_qs_by_attr(
                        Event.annotated(
                            self.request.organizer.events,
                            'web').filter(sales_channels__contains=self.
                                          request.sales_channel.identifier),
                        self.request), before, after, ebd, timezones)
                add_subevents_for_days(
                    filter_qs_by_attr(
                        SubEvent.annotated(
                            SubEvent.objects.filter(
                                event__organizer=self.request.organizer,
                                event__is_public=True,
                                event__live=True,
                                event__sales_channels__contains=self.request.
                                sales_channel.identifier).prefetch_related(
                                    'event___settings_objects',
                                    'event__organizer___settings_objects')),
                        self.request), before, after, ebd, timezones)

            data['weeks'] = weeks_for_template(ebd, self.year, self.month)
            for w in data['weeks']:
                for d in w:
                    if not d:
                        continue
                    d['events'] = self._serialize_events(d['events'] or [])
        elif list_type == "week":
            self._set_week_year()

            if hasattr(self.request, 'event'):
                tz = pytz.timezone(self.request.event.settings.timezone)
            else:
                tz = pytz.UTC

            week = isoweek.Week(self.year, self.week)
            data['week'] = [self.year, self.week]
            before = datetime(week.monday().year,
                              week.monday().month,
                              week.monday().day,
                              0,
                              0,
                              0,
                              tzinfo=tz) - timedelta(days=1)
            after = datetime(week.sunday().year,
                             week.sunday().month,
                             week.sunday().day,
                             0,
                             0,
                             0,
                             tzinfo=tz) + timedelta(days=1)

            ebd = defaultdict(list)
            if hasattr(self.request, 'event'):
                add_subevents_for_days(
                    filter_qs_by_attr(
                        self.request.event.subevents_annotated('web'),
                        self.request), before, after, ebd, set(),
                    self.request.event, kwargs.get('cart_namespace'))
            else:
                timezones = set()
                add_events_for_days(
                    self.request,
                    filter_qs_by_attr(
                        Event.annotated(self.request.organizer.events, 'web'),
                        self.request), before, after, ebd, timezones)
                add_subevents_for_days(
                    filter_qs_by_attr(
                        SubEvent.annotated(
                            SubEvent.objects.filter(
                                event__organizer=self.request.organizer,
                                event__is_public=True,
                                event__live=True,
                            ).prefetch_related(
                                'event___settings_objects',
                                'event__organizer___settings_objects')),
                        self.request), before, after, ebd, timezones)

            data['days'] = days_for_template(ebd, week)
            for d in data['days']:
                d['events'] = self._serialize_events(d['events'] or [])
        else:
            if hasattr(self.request, 'event'):
                evs = self.request.event.subevents_sorted(
                    filter_qs_by_attr(
                        self.request.event.subevents_annotated(
                            self.request.sales_channel.identifier),
                        self.request))
                tz = pytz.timezone(request.event.settings.timezone)
                data['events'] = [{
                    'name':
                    str(ev.name),
                    'location':
                    str(ev.location),
                    'date_range':
                    self._get_date_range(ev, ev.event, tz),
                    'availability':
                    self._get_availability(ev, ev.event),
                    'event_url':
                    build_absolute_uri(ev.event, 'presale:event.index'),
                    'subevent':
                    ev.pk,
                } for ev in evs]
            else:
                data['events'] = []
                qs = self._get_event_queryset()
                for event in qs:
                    tz = pytz.timezone(
                        event.cache.get_or_set(
                            'timezone', lambda: event.settings.timezone))
                    if event.has_subevents:
                        dr = daterange(event.min_from.astimezone(tz),
                                       (event.max_fromto or event.max_to
                                        or event.max_from).astimezone(tz))
                        avail = {
                            'color': 'none',
                            'text': gettext('Event series')
                        }
                    else:
                        dr = self._get_date_range(event, event, tz)
                        avail = self._get_availability(event, event)
                    data['events'].append({
                        'name':
                        str(event.name),
                        'location':
                        str(event.location),
                        'date_range':
                        dr,
                        'availability':
                        avail,
                        'event_url':
                        build_absolute_uri(event, 'presale:event.index'),
                    })

        cache.set(cache_key, data, 30)
        # These pages are cached for a really short duration – this should make them pretty accurate, while still
        # providing some protection against burst traffic.
        return self.response(data)
Example #40
0
def test_different_dates_english():
    with translation.override('en'):
        df = date(2003, 2, 1)
        dt = date(2005, 4, 3)
        assert daterange(df, dt) == "Feb. 1, 2003 – April 3, 2005"