Beispiel #1
0
 def test_sold_market_flyer_date(self):
     """ Assert when the next_flyer_date() is sold out, the user can not
     select the date to purchase flyers on the sold out date.
     """
     count = 1
     while count <= 10:
         slot = Slot(site_id=2, 
             business_id=count,
             renewal_rate=99, 
             is_autorenew=True,
             end_date=datetime.date.today() + datetime.timedelta(
                 days=count))
         slot.save()
         flyer_placement = FlyerPlacement(
             site_id=2, 
             slot=slot, 
             send_date=next_flyer_date())
         flyer_placement.save()
         count += 1
     self.prep_for_flyer_purchase()
     response = self.client.get(reverse('add-flyer-dates',
         args=[self.slot.id]))
     self.assertContains(response, 'disabled="disabled" type="checkbox" ' + 
         'name="%s" value="%s" id="id_%s" /><span class="light">' % (
         (str(date_filter(next_flyer_date(), "F j")), 
         str(next_flyer_date()), 
         str(date_filter(next_flyer_date(), "F j")))))
Beispiel #2
0
 def __init__(self, available_flyer_dates_list, 
     subdivision_consumer_count=None, checked_data=None, *args, **kwargs):
     """ Dynamically create 10 sets of location fields. """
     super(AddFlyerDatesForm, self).__init__(*args, **kwargs)
     if checked_data:
         self.fields['subdivision_consumer_count'].initial = \
         checked_data.get('subdivision_consumer_count', 0)
     else:
         self.fields['subdivision_consumer_count'].initial = \
             subdivision_consumer_count
     for flyer_month in available_flyer_dates_list:
         for week in flyer_month['weeks']:
             attrs = {'value': week['send_date']}
             if not week['date_is_available']:
                 attrs['disabled'] = 'disabled'
             if checked_data:
                 if '%s' % date_filter(week['send_date'], 'F j'
                         ) in checked_data:
                     attrs['checked'] = 'checked'
             else:    
                 if week['checked'] and week['date_is_available']:
                     attrs['checked'] = 'checked'
             self.fields['%s' % date_filter(
                 week['send_date'], 'F j')] = forms.ChoiceField(
                     widget=CheckboxInput(
                         attrs=attrs,
                         check_test=True),
                     initial=week['send_date'],
                     label = '%s' % date_filter(week['send_date'], 'F j'),
                     required=False)
Beispiel #3
0
 def common_flyer_purchase_asserts(self, response, first_purchase_date,
         second_purchase_date):
     """ Make assertions common to displaying results of flyer purchase. """
     self.assertContains(response, 'Email Flyer scheduled for %s.' %
         date_filter(first_purchase_date, "M j, Y"))
     self.assertContains(response, 'Email Flyer scheduled for %s.' %
         date_filter(second_purchase_date, "M j, Y"))
Beispiel #4
0
def nettes_datum(value, short=False):
    try:
        tzinfo = getattr(value, 'tzinfo', None)
        value = datetime.date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.datetime.now(tzinfo).date()
    delta = value - today
    datum = maybe_year

    if delta.days == 0:
        if short:
            return "heute"
        return mark_safe( "heute" + grey_span( ", " + datum(value, today) ) )
    if delta.days == 1:
        if short:
            return "morgen"
        return mark_safe( "morgen" + grey_span( ", " + datum(value, today) ) )
    if delta.days == -1:
        if short:
            return "gestern"
        return mark_safe( "gestern" + grey_span( ", " + datum(value, today) ) )
    if 1 < delta.days < 7:
        if short:
            return date_filter(value, "l")
        return mark_safe( date_filter(value, "l") + grey_span( ", " + datum(value, today) ) )
    if short:
        return date_filter(value, "D") + ", " + datum(value, today)
    return date_filter(value, "l") + ", " + datum(value, today)
Beispiel #5
0
 def __unicode__(self):
     date_format = u'l, %s' % ugettext("DATE_FORMAT")
     return ugettext('%(title)s: %(start)s-%(end)s') % {
         'title': unicode(self.event),
         'start': date_filter(self.start, date_format),
         'end': date_filter(self.end, date_format),
     }
Beispiel #6
0
def nettes_datum(value, short=False):
    try:
        tzinfo = getattr(value, "tzinfo", None)
        value = datetime.date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.datetime.now(tzinfo).date()
    delta = value - today
    datum = maybe_year

    if delta.days == 0:
        if short:
            return "heute"
        return mark_safe("heute" + grey_span(", " + datum(value, today)))
    if delta.days == 1:
        if short:
            return "morgen"
        return mark_safe("morgen" + grey_span(", " + datum(value, today)))
    if delta.days == -1:
        if short:
            return "gestern"
        return mark_safe("gestern" + grey_span(", " + datum(value, today)))
    if 1 < delta.days < 7:
        if short:
            return date_filter(value, "l")
        return mark_safe(
            date_filter(value, "l") + grey_span(", " + datum(value, today)))
    if short:
        return date_filter(value, "D") + ", " + datum(value, today)
    return date_filter(value, "l") + ", " + datum(value, today)
Beispiel #7
0
def track(request, start_date=None, end_date=None):
    if (start_date and end_date) and (start_date != end_date):
        start = datetime.strptime(start_date, '%Y-%m-%d')
        end = datetime.strptime(end_date, '%Y-%m-%d')
        position_list = PositionReport.objects.filter(
            timestamp_received__gt=start,
            timestamp_received__lt=end,
            source__display_on_maps=True).order_by('-timestamp_received')
        map_info_string = 'Showing the positions received from %s to %s' % (
            date_filter(start), date_filter(end))
    elif (start_date and not end_date) or ((start_date == end_date)
                                           and start_date):
        start = datetime.strptime(start_date, '%Y-%m-%d')
        end = start + timedelta(days=1)
        position_list = PositionReport.objects.filter(
            timestamp_received__gt=start,
            timestamp_received__lt=end,
            source__display_on_maps=True).order_by('-timestamp_received')
        map_info_string = 'Showing the positions received %s' % date_filter(
            start)
    else:
        position_list = PositionReport.objects.filter(
            source__display_on_maps=True).order_by(
                '-timestamp_received')[:NON_DATE_REPORT_LIMIT]
        map_info_string = 'Showing the last %s positions received' % NON_DATE_REPORT_LIMIT

    return render_to_response(
        'largemap.html', {
            'map_info': map_info_string,
            'positions': position_list,
            'google_maps_api_key': getattr(settings, 'GOOGLE_MAPS_KEY',
                                           'not-set'),
        },
        context_instance=RequestContext(request))
Beispiel #8
0
 def dates_display(self) -> str:
     two_months = self.start_date.month != self.end_date.month
     if two_months:
         return "{0} - {1}".format(date_filter(self.start_date, "F j"),
                                   date_filter(self.end_date, "F j, Y"))
     else:
         return "{0}-{1}".format(date_filter(self.start_date, "F j"),
                                 date_filter(self.end_date, "j, Y"))
 def hide_time_if_zero(dt):
     # Only show hours/minutes if they have been specified
     if dt.tzinfo:
         localtime = dt.astimezone(get_current_timezone())
     else:
         localtime = dt
     if localtime.hour == 0 and localtime.minute == 0:
         return date_filter(localtime, settings.DATE_FORMAT)
     return date_filter(localtime, settings.DATETIME_FORMAT)
Beispiel #10
0
 def hide_time_if_zero(dt):
     # Only show hours/minutes if they have been specified
     if dt.tzinfo:
         localtime = dt.astimezone(get_current_timezone())
     else:
         localtime = dt
     if localtime.hour == 0 and localtime.minute == 0:
         return date_filter(localtime, settings.DATE_FORMAT)
     return date_filter(localtime, settings.DATETIME_FORMAT)
Beispiel #11
0
 def test_aff_site_from_launch(self):#
     """ Assert we can post to the page to view the From Launch report. """
     affiliate_partner = MediaPartner.objects.get(id=401)
     self.login(affiliate_partner.email)
     site = Site.objects.get(id=2)
     launch_date = site.launch_date
     inception = 'From Launch Date (' + date_filter(launch_date, 'F') + ' ' \
         + date_filter(launch_date, 'Y') + ')'
     response = self.client.post('/hudson-valley/media-partner/', 
         {'report':inception})
     self.assertEqual(response.status_code, 200)
 def callback_time_string(self):
     if not self.requires_action_at:
         return None
     end_time = self.requires_action_at + datetime.timedelta(minutes=30)
     if self.callback_window_type == CALLBACK_WINDOW_TYPES.HALF_HOUR_WINDOW:
         return u"{start} - {end}".format(
             start=date_filter(localtime(self.requires_action_at), "g:iA"),
             end=date_filter(localtime(end_time), "g:iA"),
         )
     else:
         return date_filter(localtime(self.requires_action_at), "g:iA")
 def __unicode__(self):
     date_format = u'l, %s' % ugettext("DATE_FORMAT")
     result = ugettext('%(title)s: %(start)s-%(end)s') % {
         'title': unicode(self.event),
         'start': date_filter(self.start, date_format),
         'end': date_filter(self.end, date_format),
     }
     if self.rule:
         result += " repeating %s until %s" % (self.rule, date_filter(self.repeat_until, date_format))
         
     return result
    def __unicode__(self):
        date_format = u'l, %s' % ugettext("DATE_FORMAT")
        result = ugettext('%(title)s: %(start)s-%(end)s') % {
            'title': unicode(self.event),
            'start': date_filter(self.start, date_format),
            'end': date_filter(self.end, date_format),
        }
        if self.rule:
            result += " repeating %s until %s" % (
                self.rule, date_filter(self.repeat_until, date_format))

        return result
Beispiel #15
0
def create_products_list(request, site=None):
    """ Return a list of tuples of all products to be purchased """
    flyer_dates_list, add_slot_choice, add_annual_slot_choice = \
        get_selected_product(request)
    product_list = []
    if not site:
        site = get_current_site(request)
    if flyer_dates_list is not None:
        # Product for Flyers.
        pre_description = 'Email Flyer scheduled for '
        locked_flyer_price = request.session['locked_flyer_price']
        product_1_base_days = get_product_from_cache(1).base_days
        for flyer_date in flyer_dates_list:
            flyer_date = dateutil.parser.parse(flyer_date) 
            product_list.append((1, locked_flyer_price, 
                '%s%s.' % (pre_description, date_filter(flyer_date, "M j, Y")), 
                flyer_date, 
                flyer_date + datetime.timedelta(days=product_1_base_days)))
    elif add_slot_choice is not None:
        # Purchasing a Slot and Maybe a few Flyers
        try:
            slot_price = get_product_price(2, site)
        except KeyError:
            slot_price = get_locked_data(request, site)[0]
        slot_start_datetime = datetime.datetime.now()
        slot_start_date = date_filter(slot_start_datetime, "m/d/y")
        slot_end_date = datetime.date.today() + \
            dateutil.relativedelta.relativedelta(months=1)
        slot_end_datetime = datetime.datetime.combine(slot_end_date, 
            datetime.time())
        slot_description = \
            'Monthly 10Coupon Publishing Plan: %s - %s.' % (
                slot_start_date, date_filter(slot_end_date, "m/d/y"))
        product_list = [(2, slot_price, slot_description, slot_start_datetime, 
            slot_end_datetime)]
    elif add_annual_slot_choice is not None:
        slot_annual_start_datetime = datetime.datetime.now()
        slot_annual_start_date = date_filter(
            slot_annual_start_datetime, "m/d/y")
        slot_annual_end_date = datetime.date.today() + \
            dateutil.relativedelta.relativedelta(months=12)
        slot_annual_end_datetime = datetime.datetime.combine(
            slot_annual_end_date, datetime.time())
        slot_annual_description = \
            'Annual 10Coupon Publishing Plan: %s - %s.' % (
                slot_annual_start_date, date_filter(
                    slot_annual_end_date, "m/d/y"))
        product_list = [(3, get_product_price(3, site),
                         slot_annual_description, slot_annual_start_datetime, 
                         slot_annual_end_datetime)]
    return product_list
Beispiel #16
0
def table_waybills(request, queryset=ets.models.Waybill.objects.all(), filtering=None):
    """Ajax view that returns list of waybills for using in datatables"""
    
    search_string = request.GET.get("search_string", "")
    request_params = {}
    if search_string:
        request_params["search_string"] = search_string
        queryset = queryset.filter(pk__icontains=search_string)

    column_index_map = {
        0: 'order__pk',
        1: 'pk',
        2: 'order__warehouse__name',
        3: 'order__consignee__name',
        4: 'order__location__name',
        5: 'destination__name',
        6: 'transaction_type',
        7: 'transport_dispach_signed_date',
        8: 'receipt_signed_date',
        9: 'pk',
        10: 'pk',
        11: 'pk',
    }

    params = { 'filtering': filtering } if filtering else None
    redirect_url = get_api_url(request, column_index_map, "api_waybills", params, request_params )
    if redirect_url:
        return HttpResponse(simplejson.dumps({'redirect_url': redirect_url}), content_type="application/json; charset=utf-8")

    return get_datatables_records(request, queryset, column_index_map, lambda item: [
        fill_link(item.order.get_absolute_url(), item.order.pk),
        fill_link(item.get_absolute_url(), item.pk),
        item.order.warehouse.name,
        item.order.consignee.name,
        item.order.location.name,
        item.destination.name if item.destination else "",
        item.get_transaction_type_display(),
        item.transport_dispach_signed_date and date_filter(item.transport_dispach_signed_date).upper() \
                        or fill_link(item.get_absolute_url(), _("Open")),
        item.receipt_signed_date and date_filter(item.receipt_signed_date).upper() \
                        or fill_link(reverse('waybill_reception', kwargs={'waybill_pk': item.pk})
                            if item.has_receive_permission(request.user) else '', _("Receive")),
                        
        "%s/%s" % (item.validated and "D" or "-", item.receipt_validated and "R" or "-", ),
        "%s/%s" % (item.sent_compas and "D" or "-", item.receipt_sent_compas and "R" or "-", ),        
        
        fill_link(reverse('waybill_delete', kwargs={'waybill_pk': item.pk}) \
                  if item.has_delete_permission(request.user) else '',
                  _("Delete"), "delete_waybill"),
    ])
Beispiel #17
0
def _format_year_wise_date(value, same_year_format: str,
                           different_year_format: str):
    date_format = None
    if isinstance(value, date):  # `datetime` objects are also `date` objects
        date_format = same_year_format if value.year == timezone.localdate(
        ).year else different_year_format
    return date_filter(value, date_format)
Beispiel #18
0
    def items(self, obj):
        until = timezone.now().today()
        since = until - dt.timedelta(days=7)
        queryset = (Article.objects.published().filter(
            date__date__gte=since, date__date__lt=until).order_by("-date"))

        items = {}

        for article in queryset:
            date = article.date
            modified = article.modified_at
            entry = items.setdefault(
                date.date(),
                {
                    "title":
                    "Daily Digest for {}".format(date_filter(date, "jS F Y")),
                    "date":
                    date,
                    "modified":
                    modified,
                    "link":
                    obj["link"][:-1] + reverse("digest", args=(date, )),
                    "objects": [],
                },
            )
            entry["objects"].append(article)
            entry["modified"] = max(entry["modified"], modified)

        return items.values()
Beispiel #19
0
def notify_users_shift_change(sender, instance, **kwargs):
    shift = instance
    if shift.pk:
        old_shift = Shift.objects.get(pk=shift.pk)

        if old_shift.starting_time >= datetime.now() and times_changed(
                shift, old_shift):
            subject = u'Schicht wurde verändert: {task} am {date}'.format(
                task=old_shift.task.name,
                date=date_filter(old_shift.starting_time))

            message = render_to_string('shift_modification_notification.html',
                                       dict(old=old_shift, shift=shift))

            from_email = "Volunteer-Planner.org <*****@*****.**>"

            addresses = shift.helpers.values_list('user__email', flat=True)
            if addresses:
                mail = EmailMessage(subject=subject,
                                    body=message,
                                    to=['*****@*****.**'],
                                    from_email=from_email,
                                    bcc=addresses)
                logger.info(
                    u'Shift %s at %s changed: (%s-%s -> %s->%s). Sending email notification to %d affected user(s).',
                    shift.task.name, shift.facility.name,
                    old_shift.starting_time, old_shift.ending_time,
                    shift.starting_time, shift.ending_time, len(addresses))
                mail.send()
Beispiel #20
0
 def test_aff_site_current_month(self):#
     """ Assert we can post to the page to view the Current Month report."""
     affiliate_partner = MediaPartner.objects.get(id=401)
     self.login(affiliate_partner.email)
     today = datetime.today()
     payment = Payment.objects.get(id=401)
     payment.create_datetime = today
     payment.save()
     media_pie_share = MediaPieShare.objects.get(id=2)
     media_pie_share.start_date = today.date()
     media_pie_share.save()
     current_month = 'Current Month (' + date_filter(today, 'F') + ' ' + \
         date_filter(today, 'Y') + ')' 
     response = self.client.post('/hudson-valley/media-partner/', 
         {'report':current_month})
     self.assertEqual(response.status_code, 200)
def smartdate(value, arg):
    rendered = date_filter(value, arg)
    if 'c' in arg:
        rendered = re.sub(
            '(a|p)\.m\.c', lambda m: '%sm' % m.group(1), rendered)
        rendered = re.sub('(A|P)Mc', lambda m: '%s.M.' % m.group(1), rendered)
    return rendered
Beispiel #22
0
def get_event_email_data(event, email_type):
    e, v = event, event.venue
    d = dict(
        email_type=email_type,
        event_id=e.pk,
        event__title=e.title,
        event__event_url=e.get_absolute_url(force_hostname=True),
        event__tweet_count=e.tweet_count,
        event__short_url=e.get_short_url(),
        event__ticket_url=e.ticket_or_tm_url,
        event__event_date=e.event_date,
        event__event_start_time=e.event_start_time,
        event__event_timezone=e.event_timezone,
        event__venue__name=v.name,
        event__venue__address=v.address,
        event__venue__citystatezip=v.citystatezip,
        event__venue__map_url=v.map_url,
    )
    d['event__event_date'] = date_filter(d['event__event_date'], "l, N j, Y")
    if d['event__event_start_time']:
        d['event__event_start_time'] = time_filter(d['event__event_start_time'])
    if e.show_checkins:
        d['fsq_checkins'] =  v.fsq_checkins
        d['fsq_ratio'] = v.fsq_ratio_display
    return d
Beispiel #23
0
 def test_dates(self):
     self.assertLess(settings.DATES_VIDE_GRENIER['open'], settings.DATES_VIDE_GRENIER['close'])
     self.assertLess(settings.DATES_VIDE_GRENIER['close'], settings.DATES_VIDE_GRENIER['event'])
     for status in ['open', 'close', 'event']:
         self.assertIn(
             date_filter(settings.DATES_VIDE_GRENIER[status], 'j F o'),
             self.client.get(reverse('videgrenier:home')).content.decode())
Beispiel #24
0
    def test_update_details(self, logged_in_client, update_stub):
        # Arrange
        # Act
        resp = logged_in_client.get(update_stub["url"])

        # Assert
        assert resp.context["supply_chain_name"] == update_stub["sc_name"]
        assert resp.context["completion_estimation"] == date_filter(
            datetime.strptime(update_stub["sa_completion"], r"%Y-%m-%d"),
            "j F Y")
        assert (resp.context["update"].implementation_rag_rating ==
                update_stub["sau_rag"])
        assert resp.context["update"].reason_for_delays == update_stub[
            "sau_reason"]
        assert resp.context["update"].submission_date.strftime(
            r"%d.%m.%Y") == date_filter(date.today(), "d.m.Y")
Beispiel #25
0
def notify_users_shift_change(sender, instance, **kwargs):
    shift = instance
    if shift.pk:
        old_shift = Shift.objects.get(pk=shift.pk)

        if old_shift.starting_time >= datetime.now() and times_changed(shift,
                                                                       old_shift):
            subject = u'Schicht wurde verändert: {task} am {date}'.format(
                task=old_shift.task.name,
                date=date_filter(old_shift.starting_time))

            message = render_to_string('shift_modification_notification.html',
                                       dict(old=old_shift, shift=shift))

            from_email = "Volunteer-Planner.org <*****@*****.**>"

            addresses = shift.helpers.values_list('user__email', flat=True)
            if addresses:
                mail = EmailMessage(subject=subject,
                                    body=message,
                                    to=['*****@*****.**'],
                                    from_email=from_email,
                                    bcc=addresses)
                logger.info(
                    u'Shift %s at %s changed: (%s-%s -> %s->%s). Sending email notification to %d affected user(s).',
                    shift.task.name, shift.facility.name,
                    old_shift.starting_time, old_shift.ending_time,
                    shift.starting_time, shift.ending_time,
                    len(addresses))
                mail.send()
Beispiel #26
0
def get_event_email_data(event, email_type):
    e, v = event, event.venue
    d = dict(
        email_type=email_type,
        event_id=e.pk,
        event__title=e.title,
        event__event_url=e.get_absolute_url(force_hostname=True),
        event__tweet_count=e.tweet_count,
        event__short_url=e.get_short_url(),
        event__ticket_url=e.ticket_or_tm_url,
        event__event_date=e.event_date,
        event__event_start_time=e.event_start_time,
        event__event_timezone=e.event_timezone,
        event__venue__name=v.name,
        event__venue__address=v.address,
        event__venue__citystatezip=v.citystatezip,
        event__venue__map_url=v.map_url,
    )
    d['event__event_date'] = date_filter(d['event__event_date'], "l, N j, Y")
    if d['event__event_start_time']:
        d['event__event_start_time'] = time_filter(
            d['event__event_start_time'])
    if e.show_checkins:
        d['fsq_checkins'] = v.fsq_checkins
        d['fsq_ratio'] = v.fsq_ratio_display
    return d
def date_format(value, arg):
    if value is None:
        return ''

    if isinstance(value, date):
        return date_filter(value, arg=arg)

    return str(value)
Beispiel #28
0
def _render_pdf(pdf, params):
    kw = {
        'url': pdf.file.url,
        'title': pdf.title,
        'size': pdf.size,
        'date': date_filter(pdf.date, 'N jS, Y'),
    }
    return PDF_TAG % kw
Beispiel #29
0
 def prepare(self, request):
     """ Prepare the context dict for this request. """
     ad_rep = AdRep.objects.get(email=request.session['consumer']['email'])
     # Note: the resultant string itself has an embedded %s.
     link_base = '%s%s' % (ad_rep.site.domain, reverse('redirect-for-ad-rep',
         kwargs={'redirect_string': '%s' + ad_rep.url}, 
         urlconf='urls_local.urls_1'))
     # Remove / before redirect_string.
     link_base = link_base.replace('/%s', '%s')
     LOG.debug('link_base: %s' % link_base)
     my_commisions = AdRepCompensation.current_pay_period.filter(
             ad_rep=ad_rep, child_ad_rep=None).aggregate(
                 Sum('amount'))['amount__sum']
     if not my_commisions:
         my_commisions = 0
     my_teams_commisions = AdRepCompensation.current_pay_period.filter(
             ad_rep=ad_rep).exclude(child_ad_rep=None).aggregate(
                 Sum('amount'))['amount__sum']
     if not my_teams_commisions:
         my_teams_commisions = 0
     total_commisions_ever = ad_rep.ad_rep_compensations.aggregate(
                 Sum('amount'))['amount__sum']
     (start_of_pay_period, end_of_pay_period) = get_current_pay_period_dates()
     pay_period = '%s %s - %s %s' % (date_filter(start_of_pay_period, 'F'),
                                date_filter(start_of_pay_period, 'd'),
                                date_filter(end_of_pay_period, 'F'),
                                date_filter(end_of_pay_period, 'd'),)
     if not total_commisions_ever:
         total_commisions_ever = 0
     self.context.update({'ad_rep':ad_rep,
         'is_ad_rep_account': 1,
         'pay_period': pay_period, 
         'my_commisions': '$' '%.2f' % my_commisions,
         'my_teams_commisions': '$' '%.2f' % my_teams_commisions,
         'total_earnings_this_pay_period': '$' '%.2f' % (
             my_commisions + my_teams_commisions),
         'total_commisions_ever': '$' '%.2f' % total_commisions_ever,
         'how_it_works_link': link_base % reverse('how-it-works', 
             urlconf='urls_local.urls_1'),
         'recommend_enrollment_link':
             link_base % reverse('recommend-enroll',
                 urlconf='urls_local.urls_1'),
         'personal_website_link': '%s/%s/' % (ad_rep.site.domain,
             ad_rep.url) })
     return ad_rep
Beispiel #30
0
 def __str__(self):
     return "{}: {} {} {} {} {}".format(
         self.id,
         date_filter(self.datetime),
         self.liters,
         _("l"),
         self.mileage,
         _("km"),
     )
Beispiel #31
0
def live_unread_notification_list(request):
    ''' Return a json with a unread notification list '''
    try:
        user_is_authenticated = request.user.is_authenticated()
    except TypeError:  # Django >= 1.11
        user_is_authenticated = request.user.is_authenticated

    if not user_is_authenticated:
        data = {'unread_count': 0, 'unread_list': []}
        return JsonResponse(data)

    try:
        # If they don't specify, make it 5.
        num_to_fetch = request.GET.get('max', 5)
        num_to_fetch = int(num_to_fetch)
        # if num_to_fetch is negative, force at least one fetched notifications
        num_to_fetch = max(1, num_to_fetch)
        # put a sane ceiling on the number retrievable
        num_to_fetch = min(num_to_fetch, 100)
    except ValueError:
        num_to_fetch = 5  # If casting to an int fails, just make it 5.

    try:
        fetch_start_index = int(request.GET.get('start', 0))
    except ValueError:
        fetch_start_index = 0

    unread_list = []
    notifications = _get_unread_notificatons(request)

    for notification in notifications[fetch_start_index:num_to_fetch +
                                      fetch_start_index]:
        struct = model_to_dict(notification)
        timestamp_display = date_filter(
            localtime(notification.timestamp),
            dj_settings.SHORT_DATETIME_FORMAT,
        )

        struct['timestamp_display'] = timestamp_display
        struct['slug'] = id2slug(notification.id)
        if notification.actor:
            struct['actor'] = str(notification.actor)
        if notification.target:
            struct['target'] = str(notification.target)
        if notification.action_object:
            struct['action_object'] = str(notification.action_object)
        if notification.data:
            struct['data'] = notification.data
        unread_list.append(struct)
        if request.GET.get('mark_as_read'):
            notification.mark_as_read()
    data = {
        'unread_count': request.user.notifications.unread().count(),
        'unread_list': unread_list
    }
    return JsonResponse(data)
Beispiel #32
0
 def test_post_add_flyer_dates(self):
     """ Assert when a logged in advertiser selects dates from the 
     flyer-by-date page, they get pushed to the ecommerce page with the
     appropriate order items in the order summary display."""
     self.prep_for_flyer_purchase()
     first_purchase_date = next_flyer_date() + datetime.timedelta(days=14)
     second_purchase_date = next_flyer_date() + datetime.timedelta(days=28)
     first_purchase_date_key = date_filter(first_purchase_date, "F j")
     second_purchase_date_key = date_filter(second_purchase_date, "F j")
     kwargs = {
         str(first_purchase_date_key): str(first_purchase_date),
         str(second_purchase_date_key): str(second_purchase_date),
         'subdivision_consumer_count': 100}
     response = self.client.post(reverse('add-flyer-dates',
         args=[self.slot.id]), kwargs, follow=True)
     self.assertTemplateUsed(response,
         'ecommerce/display_checkout_coupon_purchase.html')
     self.common_flyer_purchase_asserts(response, first_purchase_date,
         second_purchase_date)
Beispiel #33
0
    def _add_xlsx_title(self, sheet, title, width):
        """Добавляет заголовок в документы xlsx.

        Args:
            sheet - таблица с отчетом
            title - название отчета
            widw - число ячеек под заголовок

        Returns: None
        """

        sheet.insert_rows(1)
        sheet.merge_cells(start_row=1,
                          start_column=1,
                          end_row=1,
                          end_column=width)
        cell = sheet.cell(row=1, column=1)
        cell.value = title
        cell.font = Font(size=12, bold=True, italic=True)

        sheet.insert_rows(2)
        sheet.merge_cells(start_row=2,
                          start_column=1,
                          end_row=2,
                          end_column=width)

        sheet.insert_rows(3)
        sheet.merge_cells(start_row=3,
                          start_column=1,
                          end_row=3,
                          end_column=width)
        cell = sheet.cell(row=3, column=1)
        cell.value = gettext("From {start} to {end}:").format(
            start=date_filter(self.start, "SHORT_DATE_FORMAT"),
            end=date_filter(self.end, "SHORT_DATE_FORMAT"),
        )

        sheet.insert_rows(4)
        sheet.merge_cells(start_row=4,
                          start_column=1,
                          end_row=4,
                          end_column=width)
Beispiel #34
0
def local_datetime(datetime, format_string="M. d, Y, g:i a"):
    """
        Given a date, print Javascript to print local date/time if available.
    """
    if not datetime:
        return ""
    return mark_safe("<script>document.write(localDateTime(%s, '%s'))</script><noscript>%s</noscript>" % (
        time.mktime(datetime.timetuple()),
        format_string,
        date_filter(datetime, format_string)
    ))
Beispiel #35
0
    def get_form(self, request, obj=None, **kwargs):
        # Proper kwargs are form, fields, exclude, formfield_callback
        if obj: # obj is not N  one, so this is a change page
            pass
            #kwargs['exclude'] = ['foo', 'bar',]
        else: # obj is None, so this is an add page
            kwargs['fields'] = ('date', 'user', 'resource', 'description', 'quantity', 'unit_price', 'event')

        form = super(ResourceUsageAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['description'].initial = "%s: " % date_filter(datetime.date.today(), 'SHORT_DATE_FORMAT')
        return form
Beispiel #36
0
def local_datetime(datetime, format_string="F j, Y g:m a"):
    """
        Given a date, print Javascript to print local date/time if available.
    """
    if not datetime:
        return ""
    random_id = 'date_' + str(random.random())[2:]
    return mark_safe(
        "<script id='%s'>insertLocalDateTime('%s', %s, '%s')</script><noscript>%s</noscript>"
        % (random_id, random_id, calendar.timegm(datetime.utctimetuple()),
           format_string, date_filter(datetime, format_string)))
Beispiel #37
0
    def _add_docx_title(self, document, title):
        """Добавляет заголовок в документы docx.

        Args:
            document - документ с отчетом
            title - название отчета

        Returns: None
        """

        heading = document.add_heading(title, level=1)
        heading.add_run().add_break()
        paragraph = document.add_paragraph(_('From '))
        paragraph.add_run(date_filter(self.start,
                                      "SHORT_DATE_FORMAT")).bold = True
        paragraph.add_run(_(' to '))
        paragraph.add_run(date_filter(self.end,
                                      "SHORT_DATE_FORMAT")).bold = True
        paragraph.add_run(':')
        paragraph.add_run().add_break()
    def test_renders_completion_dates(self):

        response = self.client.get(self.url)

        pixel_set = models.PixelSet.objects.get()

        expected = ('<span class="completed-at">'
                    'Completion date: {}'
                    '</span>')
        self.assertContains(response,
                            expected.format(
                                date_filter(pixel_set.analysis.completed_at)),
                            count=1,
                            html=True)
        self.assertContains(
            response,
            expected.format(
                date_filter(
                    pixel_set.analysis.experiments.get().completed_at)),
            count=1,
            html=True)
def track(request, start_date=None, end_date=None):
    if (start_date and end_date) and (start_date != end_date):
        start = datetime.strptime(start_date, '%Y-%m-%d')
        end = datetime.strptime(end_date, '%Y-%m-%d')
        position_list = PositionReport.objects.filter(timestamp_received__gt=start, timestamp_received__lt=end, source__display_on_maps=True).order_by('-timestamp_received')
        map_info_string = 'Showing the positions received from %s to %s' % (date_filter(start), date_filter(end))
    elif (start_date and not end_date) or ((start_date == end_date) and start_date):
        start = datetime.strptime(start_date, '%Y-%m-%d')
        end = start + timedelta(days=1)
        position_list = PositionReport.objects.filter(timestamp_received__gt=start, timestamp_received__lt=end, source__display_on_maps=True).order_by('-timestamp_received')
        map_info_string = 'Showing the positions received %s' % date_filter(start)
    else:
        position_list = PositionReport.objects.filter(source__display_on_maps=True).order_by('-timestamp_received')[:NON_DATE_REPORT_LIMIT]
        map_info_string = 'Showing the last %s positions received' % NON_DATE_REPORT_LIMIT

    return render_to_response('largemap.html',
    {
        'map_info': map_info_string,
        'positions': position_list,
        'google_maps_api_key': getattr(settings, 'GOOGLE_MAPS_KEY', 'not-set'),
    }, context_instance=RequestContext(request))
Beispiel #40
0
def local_datetime(datetime, format_string="MMM DD, YYYY h:m a"):
    """
        Given a date, print Javascript to print local date/time if available.
    """

    if not datetime:
        return ""
    return mark_safe("<script>document.write(moment('%s').format('%s'))</script><noscript>%s</noscript>" % (
        datetime,
        format_string,
        date_filter(datetime, format_string)
    ))
Beispiel #41
0
        def wrapper(*args, **kwargs):
            value = func(*args, **kwargs)

            if not hasattr(value, 'date'):
                return value

            if value.date() == compare_date:
                format = time_format
            else:
                format = datetime_format

            return date_filter(value, format)
Beispiel #42
0
def humanize_date(value, arg='j F Y'):
    if isinstance(value, datetime):
        value = Pendulum.instance(value)
    elif isinstance(value, date):
        value = Pendulum.create(year=value.year,
                                month=value.month,
                                day=value.day)

    result = naturalweekday(value)
    if abs(Pendulum.now().diff(value).in_days()) > 2:
        result += ' ' + date_filter(value, arg)
    return result
 def test_checkout_flyer_dates(self):
     """ Assert multiple flyer dates get purchased for this advertisers slot.
     Assert no FlyerPlacementSubdivisions get inserted into the db since this
     purchase is for the entire market.
     """
     kwargs = {'email':'*****@*****.**',
             'consumer_zip_postal':'10990',
             'business_name':'purchase flyer dates',
             'short_business_name':'purchase flyer dates',
             'headline':'purchase flyer dates'}
     self.make_advertiser_with_slot(**kwargs)
     SlotTimeFrame.objects.create(slot_id=self.slot.id,
         coupon_id=self.advertiser.businesses.all(
             )[0].offers.all()[0].coupons.all()[0].id)
     self.login_build_set_assemble(self.advertiser)
     self.session['current_slot_id'] = self.slot.id
     first_purchase_date = next_flyer_date()
     second_purchase_date = next_flyer_date() + datetime.timedelta(days=28)
     third_purchase_date = next_flyer_date() + datetime.timedelta(days=42)
     self.assertEqual(0, FlyerPlacement.objects.filter(slot__id=self.slot.id,
         send_date=first_purchase_date).count())
     self.assertEqual(0, FlyerPlacement.objects.filter(slot__id=self.slot.id,
         send_date=second_purchase_date).count())
     self.assertEqual(0, FlyerPlacement.objects.filter(slot__id=self.slot.id,
         send_date=third_purchase_date).count())
     flyer_subdivision_count = FlyerPlacementSubdivision.objects.count()
     flyer_dates_list = [unicode(first_purchase_date),
                         unicode(second_purchase_date),
                         unicode(third_purchase_date)]
     self.session['flyer_dates_list'] = flyer_dates_list
     self.create_product_list(self.advertiser.site)
     self.assemble_session(self.session)
     response = self.client.post(reverse('checkout-coupon-purchase'),
         data=self.test_credit_card_data_complete, follow=True)
     # Display checkout page. Redirected (followed).
     self.assertEqual(response.status_code, 200)
     self.assertEqual(str(response.request['PATH_INFO']), 
         '/hudson-valley/create-coupon/checkout-success/')
     self.common_flyer_purchase_asserts(response, first_purchase_date,
         second_purchase_date)
     self.assertContains(response,
         'Email Flyer scheduled for %s.' % 
         date_filter(third_purchase_date, "M j, Y"))
     self.assertEqual(1, FlyerPlacement.objects.filter(slot__id=self.slot.id,
         send_date=first_purchase_date).count())
     self.assertEqual(1, FlyerPlacement.objects.filter(slot__id=self.slot.id,
         send_date=second_purchase_date).count())
     self.assertEqual(1, FlyerPlacement.objects.filter(slot__id=self.slot.id,
         send_date=third_purchase_date).count())
     # Make sure no subdivision got inserted for this flyer placement since
     # the flyers were being purchased for the entire market.
     self.assertEqual(flyer_subdivision_count,
         FlyerPlacementSubdivision.objects.count())
Beispiel #44
0
 def test_get_add_flyer_dates(self):
     """ Assert a logged in advertiser can get to the purchase flyer-by-date
     page with the default checked and previous days in the month not
     checked. """
     self.prep_for_flyer_purchase()
     response = self.client.get(reverse('add-flyer-dates',
         args=[self.slot.id]))
     self.assertContains(response,
         self.advertiser.site.get_or_set_consumer_count())
     self.assertContains(response, 
         'checked="checked" name="%s" value="%s"' %
             (str(date_filter(next_flyer_date(), "F j")),
             str(next_flyer_date())))
     if int(date_filter(next_flyer_date(), "j")) > 7:
         previous_date = next_flyer_date() + datetime.timedelta(days=-7)
         self.assertContains(response,
             'disabled="disabled" type="checkbox" ' +
             'name="%s" value="%s" id="id_%s" /><span class="light">' % (
             (str(date_filter(previous_date, "F j")),
              str(previous_date),
              str(date_filter(previous_date, "F j")))))
Beispiel #45
0
def table_validate_waybills(request, queryset=ets.models.Waybill.objects.all(), filtering=None):
    """Ajax view that returns list of validated/not validated waybills for using in datatables"""
    
    if filtering in ["dispatch_validated", "validate_dispatch"]:
        url = "validate_dispatch"
        logger_action = ets.models.CompasLogger.DISPATCH
        queryset = queryset.filter(**get_dispatch_compas_filters(request.user))
    elif filtering in ["receipt_validated", "validate_receipt"]:
        url = "validate_receipt"
        logger_action = ets.models.CompasLogger.RECEIPT
        queryset = queryset.filter(**get_receipt_compas_filters(request.user))
        
    column_index_map = {
        0: 'order__pk',
        1: 'pk',
        2: 'order__warehouse__name',
        3: 'order__consignee__name',
        4: 'order__location__name',
        5: 'transport_dispach_signed_date',
        6: 'receipt_signed_date',
        7: 'pk',
        8: 'pk',
    }

    params = { 'filtering': filtering } if filtering else None
    redirect_url = get_api_url(request, column_index_map, "api_waybills", params)
    if redirect_url:
        return HttpResponse(simplejson.dumps({'redirect_url': redirect_url}), content_type="application/json; charset=utf-8")

    return get_datatables_records(request, queryset, column_index_map, lambda item: [
        fill_link(item.order.get_absolute_url(), item.order.pk),
        fill_link(item.get_absolute_url(), item.pk),
        item.order.warehouse.name,
        item.order.consignee.name,
        item.order.location.name,
        item.transport_dispach_signed_date and date_filter(item.transport_dispach_signed_date).upper() or _("Pending"),
        item.receipt_signed_date and date_filter(item.receipt_signed_date).upper() or _("Pending"),
        fill_link(reverse(url, kwargs={'waybill_pk': item.pk}), _("Validate"), "validate-link"),
        fill_link(reverse("waybill_errors", kwargs={'waybill_pk': item.pk, "logger_action": logger_action}), _("Show errors"), "error-link") if item.compass_loggers.filter(action=logger_action).exists() else "",
    ])
def datetime_string_format(value):
    """
    :param value: String - Expected to be a datetime, date, or time in specific format
    :return: String - reformatted to default datetime, date, or time string if received in one of the expected formats
    """
    try:
        new_value = date_filter(
            datetime.strptime(value, CUSTOMFIELD_DATETIME_FORMAT),
            settings.DATETIME_FORMAT)
    except ValueError:
        try:
            new_value = date_filter(
                datetime.strptime(value, CUSTOMFIELD_DATE_FORMAT),
                settings.DATE_FORMAT)
        except ValueError:
            try:
                new_value = date_filter(
                    datetime.strptime(value, CUSTOMFIELD_TIME_FORMAT),
                    settings.TIME_FORMAT)
            except ValueError:
                new_value = value
    return new_value
    def test_renders_release_date(self):

        response = self.client.get(self.url)

        expected = ('<span class="released-at">' 'Release date: {}' '</span>')

        self.assertContains(
            response,
            expected.format(
                date_filter(
                    self.pixel_set.analysis.experiments.get().released_at)),
            count=1,
            html=True)
Beispiel #48
0
def datetime_string_format(value):
    """
    :param value: String - Expected to be a datetime, date, or time in specific format
    :return: String - reformatted to default datetime, date, or time string if received in one of the expected formats
    """
    try:
        new_value = date_filter(
            datetime.strptime(value, CUSTOMFIELD_DATETIME_FORMAT),
            settings.DATETIME_FORMAT)
    except (TypeError, ValueError):
        try:
            new_value = date_filter(
                datetime.strptime(value, CUSTOMFIELD_DATE_FORMAT),
                settings.DATE_FORMAT)
        except (TypeError, ValueError):
            try:
                new_value = date_filter(
                    datetime.strptime(value, CUSTOMFIELD_TIME_FORMAT),
                    settings.TIME_FORMAT)
            except (TypeError, ValueError):
                # If NoneType return empty string, else return original value
                new_value = "" if value is None else value
    return new_value
Beispiel #49
0
	def applications_matching_search(self, application_list):
		search_form = self

		name = search_form.cleaned_data['name']
		if name:
			application_list = [application for application in application_list if
								name.lower() in application.user.get_full_name().lower()]

		programme = search_form.cleaned_data['programme']
		if programme:
			application_list = [application for application in application_list if
								programme == application.user.profile.programme]

		submission_date = search_form.cleaned_data['submission_date']
		if submission_date:
			application_list = [application for application in application_list if
								submission_date.lower() in date_filter(
									application.submission_date + timezone.timedelta(hours=2), "d M H:i").lower()]

		role = search_form.cleaned_data['role']
		priority = (search_form.cleaned_data['priority']) # A string: 0, 1, or 2

		# Three different search cases: role + priority, only role or only priority
		if role and priority:
			application_list = [application for application in application_list if (role, int(priority)) in [(roleapp.role, roleapp.order) for roleapp in application.roles]]
		elif role:
			application_list = [application for application in application_list if role in [roleapp.role for roleapp in application.roles]]
		elif priority:
			# Rare use case, matches all applications where any role has been chosen with the given priority
			application_list = [application for application in application_list if int(priority) in [roleapp.order for roleapp in application.roles]]

		interviewer = search_form.cleaned_data['interviewer']
		if interviewer:
			application_list = [application for application in application_list if
								interviewer == application.interviewer]

		recommended_role = search_form.cleaned_data['recommended_role']
		if recommended_role:
			application_list = [application for application in application_list if
								recommended_role == application.recommended_role]

		rating = search_form.cleaned_data['rating']
		if rating:
			application_list = [application for application in application_list if int(rating) == application.rating]

		state = search_form.cleaned_data['state']
		if state:
			application_list = [application for application in application_list if state == application.state()]

		return application_list
Beispiel #50
0
def local_datetime(datetime, format_string="F j, Y g:m a"):
    """
        Given a date, print Javascript to print local date/time if available.
    """
    if not datetime:
        return ""
    random_id = 'date_'+str(random.random())[2:]
    return mark_safe("<script id='%s'>insertLocalDateTime('%s', %s, '%s')</script><noscript>%s</noscript>" % (
        random_id,
        random_id,
        calendar.timegm(datetime.utctimetuple()),
        format_string,
        date_filter(datetime, format_string)
    ))
Beispiel #51
0
def table_orders(request, queryset):
    """Ajax view that returns list of orders for using in datatables"""
    column_index_map = {
        0: 'code',
        1: 'created',
        2: 'dispatch_date',
        3: 'expiry',
        4: 'warehouse__name',
        5: 'location__name',
        6: 'consignee__code',
        7: 'transport_name',
        8: 'code',
        9: 'code',
        10: 'code',
    }
    
    queryset = queryset.filter(**filter_for_orders())

    redirect_url = get_api_url(request, column_index_map, "api_orders")
    if redirect_url:
        return HttpResponse(simplejson.dumps({'redirect_url': redirect_url}), content_type="application/json; charset=utf-8")

    return get_datatables_records(request, queryset, column_index_map, lambda item: [
        fill_link(item.get_absolute_url(), item.code),
        date_filter(item.created).upper(),
        date_filter(item.dispatch_date).upper(),
        date_filter(item.expiry).upper(),
        item.warehouse.name,
        item.location.name,
        unicode(item.consignee),
        item.transport_name,
        item.percentage,
        fill_link(reverse('waybill_create', kwargs={'order_pk': item.pk}) \
                  if item.has_waybill_creation_permission(request.user) else '', 
                  _("Create")),
        item.is_expired(),
        ])
Beispiel #52
0
def calendar(context, booking_list):
    start = date.today()
    end = date.today() + timedelta(days=config.BOOKING_DAYS_FUTURE)

    bookings_by_day = group_by(booking_list, lambda b: b.date)

    output = []
    for d in date_range(start, end):
        if d < date.today():
            output.append(format_html('<h4 class="page-header text-muted">{}</h4>', date_filter(d, 'l j \d\e F')))
        elif d == date.today():
            output.append(format_html('<h4 class="page-header text-warning"><b>{} (hoy)</b></h4>', date_filter(d, 'l j \d\e F')))
        else:
            output.append(format_html('<h4 class="page-header">{}</h4>', date_filter(d, 'l j \d\e F')))

        if bookings_by_day.get(d, None):
            output.append('<div class="list-group">')
            for booking in bookings_by_day[d]:
                if booking.status != 'x' and booking.user == context['request'].user:
                    actions = format_html('<a class="btn btn-xs btn-link" href="{}">Cancelar</a>', reverse('bookings:cancel', kwargs={'pk': booking.pk}))
                else:
                    actions = ''

                label_classes = {'x': 'danger', 'c': 'success', 'p': 'warning'}

                output.append(format_html('<div class="list-group-item"><div class="row"><div class="col-md-4">{} {}</div> <div class="col-md-6"><span style="position: relative; top: 1px; font-weight: bold;">{}</span></div><div class="col-md-2 text-right">{}</div></div></div>',
                    format_html('<span class="label label-{}">{}</span>', label_classes[booking.status], booking.get_status_display()),
                    format_html('<span class="label label-info">Turno {}</span>', booking.get_shift_display()),
                    format_html('<span data-toggle="tooltip" title="{}">{}</span>', booking.user.email, booking.user.get_full_name()),
                    actions,
                ))
            output.append('</div>')
        else:
            output.append(format_html('<p class="text-muted">{}</p>', 'No hay reservas para este día.'))

    return mark_safe(''.join(output))
Beispiel #53
0
    def get_time_series_field_verbose_name(cls, date_period, index, dates,
                                           pattern):
        """
        Get the name of the verbose name of a computaion field that's in a time_series.
        should be a mix of the date period if the column an it's verbose name.
        :param date_period: a tuple of (start_date, end_date)
        :param index: the index of the current field in the whole dates to be calculated
        :param dates a list of tuples representing the start and the end date
        :return: a verbose string
        """
        dt_format = '%Y/%m/%d'

        if pattern == 'monthly':
            month_name = date_filter(date_period[0], 'F Y')
            return f'{cls.verbose_name} {month_name}'
        elif pattern == 'daily':
            return f'{cls.verbose_name} {date_period[0].strftime(dt_format)}'
        elif pattern == 'weekly':
            return f' {cls.verbose_name} {_("Week")} {index} {date_period[0].strftime(dt_format)}'
        elif pattern == 'yearly':
            year = date_filter(date_period[0], 'Y')
            return f'{cls.verbose_name} {year}'

        return f'{cls.verbose_name} {date_period[0].strftime(dt_format)} - {date_period[1].strftime(dt_format)}'
Beispiel #54
0
def format_datetime(dt, format=None):
    """
    Takes an instance of datetime, converts it to the current timezone and
    formats it as a string. Use this instead of
    django.core.templatefilters.date, which expects localtime.
    :param format: Common will be settings.DATETIME_FORMAT or
                   settings.DATE_FORMAT, or the resp. shorthands
                   ('DATETIME_FORMAT', 'DATE_FORMAT')
    """
    if is_naive(dt):
        localtime = make_aware(dt, get_current_timezone())
        logging.warning(
            "helpers.utils.format_datetime received native datetime")
    else:
        localtime = dt.astimezone(get_current_timezone())
    return date_filter(localtime, format)
Beispiel #55
0
    def make_pdf(self):
        reg = self.registration
        event = reg.event
        address = f"""
_{reg.letter.name}_\u0020\u0020
_{reg.letter.address}_
"""
        intro = f"""
On behalf of the {event.name} organizing committee, I would hereby like to invite

_Name: **{reg.letter.name}**_\u0020\u0020
_Passport number: **{reg.letter.passport_number}**_\u0020\u0020
_Nationality: **{reg.letter.nationality}**_\u0020\u0020

to attend the \u201C{event.full_name} ({event.name})\u201D
from {date_filter(event.start_date)} to {date_filter(event.end_date)}
in {event.city}, {event.country.name}.
"""
        signature = f"""
More information about this event can be found on:\u0020\u0020
<{event.website}>

We look forward to welcoming {reg.letter.name} in {event.city}.\u0020\u0020
Please do not hesitate to contact me for additional information.\u0020\u0020
Sincerely yours,
"""

        with Pdf() as pdf:
            pdf.add_text(date_filter(timezone.now()), "p_right")
            pdf.add_text(address, "p_small", "markdown")
            pdf.add_spacer(1.5)
            pdf.add_text("To Whom It May Concern,")
            pdf.add_text(intro, "p", "markdown")

            if reg.letter.submitted:
                paper = f"""
{reg.user.profile.name} has submitted a {reg.letter.submitted} titled \u2018{reg.letter.submitted_title}\u2019
with the intention to present it during the event.
"""
                pdf.add_text(paper, "p", "markdown")

            pdf.add_text(signature, "p", "markdown")
            pdf.add_spacer(1.5)
            pdf.add_text(event.signature, "p", "markdown")
            pdf.add_page_break()

            self._response.write(pdf.get())
Beispiel #56
0
def format_datetime(dt, format=None):
    """
    Takes an instance of datetime, converts it to the current timezone and
    formats it as a string. Use this instead of
    django.core.templatefilters.date, which expects localtime.

    :param format: Common will be settings.DATETIME_FORMAT or
                   settings.DATE_FORMAT, or the resp. shorthands
                   ('DATETIME_FORMAT', 'DATE_FORMAT')
    """
    if is_naive(dt):
        localtime = make_aware(dt, get_current_timezone())
        logging.warning(
            "oscar.core.utils.format_datetime received native datetime")
    else:
        localtime = dt.astimezone(get_current_timezone())
    return date_filter(localtime, format)
Beispiel #57
0
    def get_context_data(self, **kwargs):
        context = super(ContestCalendar, self).get_context_data(**kwargs)

        try:
            month = date(self.year, self.month, 1)
        except ValueError:
            raise Http404()
        else:
            context['title'] = _('Contests in %(month)s') % {
                'month': date_filter(month, _("F Y"))
            }

        dates = Contest.objects.aggregate(min=Min('start_time'),
                                          max=Max('end_time'))
        min_month = (self.today.year, self.today.month)
        if dates['min'] is not None:
            min_month = dates['min'].year, dates['min'].month
        max_month = (self.today.year, self.today.month)
        if dates['max'] is not None:
            max_month = max((dates['max'].year, dates['max'].month),
                            (self.today.year, self.today.month))

        month = (self.year, self.month)
        if month < min_month or month > max_month:
            # 404 is valid because it merely declares the lack of existence, without any reason
            raise Http404()

        context['now'] = timezone.now()
        context['calendar'] = self.get_table()
        context['curr_month'] = date(self.year, self.month, 1)

        if month > min_month:
            context['prev_month'] = date(
                self.year - (self.month == 1),
                12 if self.month == 1 else self.month - 1, 1)
        else:
            context['prev_month'] = None

        if month < max_month:
            context['next_month'] = date(
                self.year + (self.month == 12),
                1 if self.month == 12 else self.month + 1, 1)
        else:
            context['next_month'] = None
        return context
Beispiel #58
0
def send_favorites(hours=25, queue=None, limit_to_username=None):
    from event.models import RecommendedEvent, Event
    from event.templatetags.eventtags import event_friends
    from registration.models import UserProfile
    now = date.today()
    add_date_threshold = date.today() - timedelta(hours=hours)
    profiles = UserProfile.objects.active().filter(
        send_favorites=True).order_by('pk')
    if limit_to_username:
        profiles = profiles.filter(user__username=limit_to_username)
    n = 0
    q = queue or EventsQ(bind_queue=False)
    for p in profiles:
        a = p.user
        d = dict(email_type='favorites',
                 attendee__username=a.username,
                 attendee__email=a.email,
                 attendee__first_name=a.first_name,
                 attendee__last_name=a.last_name,
                 attendee_profile_id=p.pk)
        picks = Event.objects.active().select_related('artist').filter(
            recommendedevent__user_profile=p,
            recommendedevent__added_on__gte=add_date_threshold,
        ).distinct().order_by('event_date', 'event_start_time')
        if picks:
            ripe_picks = []
            d['ripe_picks'] = ripe_picks
            for rp in picks:
                ripe = dict(
                    event__event_url=rp.get_absolute_url(force_hostname=True),
                    event__title=rp.title,
                    event__event_date=date_filter(rp.event_date, "l, N j, Y"),
                    event__event_start_time=time_filter(rp.event_start_time),
                    event__event_timezone=rp.event_timezone,
                )
                ripe_picks.append(ripe)
                num_fr = event_friends(rp, p).lower().replace('| ', '')
                if num_fr.endswith("friend"):
                    num_fr = "<b>" + num_fr + "</b> is interested in"
                elif num_fr.endswith("friends"):
                    num_fr = "<b>" + num_fr + "</b> are interested in"
                ripe['num_friends'] = num_fr
            send_event_reminder(d, queue=q, email_type='favorites')
            n += 1
    _log.debug("%s event favorite emails sent", n)
Beispiel #59
0
def digest_for_date(date: dt.date) -> None:
    articles = Article.objects.published().for_date(date).order_by("-date")

    if articles.count() == 0:
        return

    scheme = settings.SITE_SCHEME
    site = Site.objects.get_current()
    title = "Digest for {}".format(date_filter(date, "jS F Y"))
    sender = settings.DEFAULT_FROM_EMAIL

    for subscription in Subscription.objects.confirmed():

        cancel_url = "{}://{}{}?action=cancel&token={}".format(
            scheme, site.domain, reverse("subscribe"), subscription.token)

        context = {
            "title": title,
            "date": date,
            "site_name": site.name,
            "objects": articles,
            "receiver": subscription.email,
            "cancel_url": cancel_url,
        }

        template = "lynx/emails/digest_body.html"
        formatted = get_template(template).render(context)
        inlined = inline_css(formatted)
        template = "lynx/emails/digest_body.txt"
        plain = get_template(template).render(context)

        Email.objects.create(
            sender=sender,
            receivers=subscription.email,
            subject=title,
            formatted=inlined,
            plain=plain,
            sent_at=None,
        )