示例#1
0
文件: helpers.py 项目: tantek/kuma
def datetimeformat(context, value, format='shortdatetime'):
    """
    Returns date/time formatted using babel's locale settings. Uses the
    timezone from settings.py
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError

    tzinfo = timezone(settings.TIME_ZONE)
    tzvalue = tzinfo.localize(value)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = _lazy(u'Today at %s') % format_time(
                                    tzvalue, format='short', locale=locale)
        else:
            formatted = format_datetime(tzvalue, format='short', locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        formatted = format_date(tzvalue, locale=locale)
    elif format == 'time':
        formatted = format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % \
                         (tzvalue.isoformat(), formatted))
示例#2
0
def datetimeformat(context, value, format='shortdatetime'):
    """
    Returns a formatted date/time using Babel's locale settings. Uses the
    timezone from settings.py, if the user has not been authenticated.
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError

    request = context.get('request')

    default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
    if value.tzinfo is None:
        value = default_tzinfo.localize(value)
        new_value = value.astimezone(default_tzinfo)
    else:
        new_value = value

    if 'timezone' not in request.session:
        if request.user.is_authenticated():
            try:
                convert_tzinfo = request.user.get_profile().timezone or \
                                 default_tzinfo
            except (Profile.DoesNotExist, AttributeError):
                pass
        request.session['timezone'] = convert_tzinfo
    else:
        convert_tzinfo = request.session['timezone']

    convert_value = new_value.astimezone(convert_tzinfo)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
        if convert_value.toordinal() == today:
            formatted = _lazy(u'Today at %s') % format_time(
                convert_value, format='short', tzinfo=convert_tzinfo,
                locale=locale)
        else:
            formatted = format_datetime(convert_value, format='short',
                tzinfo=convert_tzinfo, locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(convert_value, format='long',
            tzinfo=convert_tzinfo, locale=locale)
    elif format == 'date':
        formatted = format_date(convert_value, locale=locale)
    elif format == 'time':
        formatted = format_time(convert_value, tzinfo=convert_tzinfo,
            locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(convert_value, tzinfo=convert_tzinfo,
            locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % \
                         (convert_value.isoformat(), formatted))
示例#3
0
 def _get_mime_headers(self):
     headers = []
     headers.append(('Project-Id-Version',
                     '%s %s' % (self.project, self.version)))
     headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address))
     headers.append(('POT-Creation-Date',
                     format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ',
                                     locale='en')))
     if isinstance(self.revision_date, (datetime, time_) + number_types):
         headers.append(('PO-Revision-Date',
                         format_datetime(self.revision_date,
                                         'yyyy-MM-dd HH:mmZ', locale='en')))
     else:
         headers.append(('PO-Revision-Date', self.revision_date))
     headers.append(('Last-Translator', self.last_translator))
     if (self.locale is not None) and ('LANGUAGE' in self.language_team):
         headers.append(('Language-Team',
                        self.language_team.replace('LANGUAGE',
                                                   str(self.locale))))
     else:
         headers.append(('Language-Team', self.language_team))
     if self.locale is not None:
         headers.append(('Plural-Forms', self.plural_forms))
     headers.append(('MIME-Version', '1.0'))
     headers.append(('Content-Type',
                     'text/plain; charset=%s' % self.charset))
     headers.append(('Content-Transfer-Encoding', '8bit'))
     headers.append(('Generated-By', 'Babel %s\n' % VERSION))
     return headers
示例#4
0
 def export2json(export):
     # TODO: This doesn't actually work, I can't figure out how to get
     #       the corect data out of redis
     if export.status != 'complete':
         data = redis.hgetall(export.redis_key)
     else:
         data = {}
     log.debug('info: {}'.format(str(data)))
     count = len(export.contents)
     return {
         'id': export.id,
         'title': localizer.pluralize(
             _(u'Export containing ${count} item'),
             _(u'Export containing ${count} items'),
             count, 'occams', mapping={'count': count}),
         'name': export.name,
         'status': export.status,
         'use_choice_labels': export.use_choice_labels,
         'expand_collections': export.expand_collections,
         'contents': sorted(export.contents, key=lambda v: v['title']),
         'count': data.get('count'),
         'total': data.get('total'),
         'file_size': (naturalsize(export.file_size)
                       if export.file_size else None),
         'download_url': request.route_path('studies.export_download',
                                            export=export.id),
         'delete_url': request.route_path('studies.export',
                                          export=export.id),
         'create_date': format_datetime(export.create_date, locale=locale),
         'expire_date': format_datetime(export.expire_date, locale=locale)
     }
def pretty_time(dt, allow_relative=True):
    ago = datetime.datetime.now(pytz.UTC) - dt

    if allow_relative and ago < datetime.timedelta(hours=24):
        return template_helpers.simplified_timesince(dt)
    elif dt.date() == datetime.datetime.now(pytz.UTC).date():
        return format_datetime(
            datetime=dt,
            tzinfo=pytz.UTC,
            format="HH:mm",
            locale=c.locale,
        )
    elif ago < datetime.timedelta(days=365):
        return format_datetime(
            datetime=dt,
            tzinfo=pytz.UTC,
            format="dd MMM HH:mm",
            locale=c.locale,
        )
    else:
        return format_datetime(
            datetime=dt,
            tzinfo=pytz.UTC,
            format="dd MMM YYYY HH:mm",
            locale=c.locale,
        )
示例#6
0
def getRSSFeed(items):
    # XML Header
    rssContent = '<?xml version="1.0" encoding="iso-8859-1"?>\r\n'
    rssContent += '<rss version="2.0">\r\n'
    rssContent += "\t<channel>\r\n"
    rssContent += "\t\t<title>XDM RSS Feed - AutoGet-It</title>\r\n"
    rssContent += "\t\t<link>http://xdm.lad1337.de</link>\r\n"
    rssContent += "\t\t<description>RSS feed generated by XDM to download.</description>\r\n"
    rssContent += "\t\t<lastBuildDate>%s</lastBuildDate>\r\n" % format_datetime(
        datetime.datetime.now(), "E, d MMM yyyy HH:mm:ss", locale="en_US"
    )
    rssContent += "\t\t<generator>XDM RSS downloader Plugin</generator>\r\n\r\n"

    # XML Content
    for item in items:
        rssContent += "\t\t<item>\r\n"
        rssContent += "\t\t\t<title>%s</title>\r\n" % item["title"]
        rssContent += "\t\t\t<link>%s</link>\r\n" % item["link"]
        rssContent += "\t\t\t<guid>%s</guid>\r\n" % item["guid"]
        rssContent += "\t\t\t<pubDate>%s</pubDate>\r\n" % format_datetime(
            item["pubDate"], "E, d MMM yyyy HH:mm:ss", locale="en_US"
        )
        rssContent += "\t\t</item>\r\n"

    # XML Footer
    rssContent += "\t</channel>\r\n</rss>\r\n"
    return rssContent
示例#7
0
 def _get_mime_headers(self):
     headers = []
     headers.append(('Project-Id-Version',
                     '%s %s' % (self.project, self.version)))
     headers.append(('Report-Msgid-Bugs-To', self.msgid_bugs_address))
     headers.append(('POT-Creation-Date',
                     format_datetime(self.creation_date, 'yyyy-MM-dd HH:mmZ',
                                     locale='en')))
     if self.locale is None:
         headers.append(('PO-Revision-Date', 'YEAR-MO-DA HO:MI+ZONE'))
         headers.append(('Last-Translator', 'FULL NAME <EMAIL@ADDRESS>'))
         headers.append(('Language-Team', 'LANGUAGE <*****@*****.**>'))
     else:
         headers.append(('PO-Revision-Date',
                         format_datetime(self.revision_date,
                                         'yyyy-MM-dd HH:mmZ', locale='en')))
         headers.append(('Last-Translator', self.last_translator))
         headers.append(('Language-Team',
                        self.language_team.replace('LANGUAGE',
                                                   str(self.locale))))
         headers.append(('Plural-Forms', self.plural_forms))
     headers.append(('MIME-Version', '1.0'))
     headers.append(('Content-Type',
                     'text/plain; charset=%s' % self.charset))
     headers.append(('Content-Transfer-Encoding', '8bit'))
     headers.append(('Generated-By', 'Babel %s\n' % VERSION))
     return headers
def pretty_time(dt):
    display_tz = pytz.timezone(c.liveupdate_event.timezone)
    today = datetime.datetime.now(display_tz).date()
    date = dt.astimezone(display_tz).date()

    if date == today:
        return format_time(
            time=dt,
            tzinfo=display_tz,
            format="HH:mm z",
            locale=c.locale,
        )
    elif today - date < datetime.timedelta(days=365):
        return format_datetime(
            datetime=dt,
            tzinfo=display_tz,
            format="dd MMM HH:mm z",
            locale=c.locale,
        )
    else:
        return format_datetime(
            datetime=dt,
            tzinfo=display_tz,
            format="dd MMM YYYY HH:mm z",
            locale=c.locale,
        )
示例#9
0
def formatDateTime(dateTime, showWeek=False, format=None, locale=None):
    week = ""
    locale = str(locale or currentLocale())
    if showWeek:
        week = "EEEE "
    if not format:
        return format_datetime(dateTime, week+'d/M/yyyy H:mm', locale=locale).encode('utf-8')
    else:
        return format_datetime(dateTime, format, locale=locale).encode('utf-8')
示例#10
0
def datetimeformat(context, value, format="shortdatetime"):
    """
    Returns a formatted date/time using Babel's locale settings. Uses the
    timezone from settings.py, if the user has not been authenticated.
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError("Unexpected value {value} passed to datetimeformat".format(value=value))

    request = context.get("request")

    default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
    if value.tzinfo is None:
        value = default_tzinfo.localize(value)
        new_value = value.astimezone(default_tzinfo)
    else:
        new_value = value

    if "timezone" not in request.session:
        if request.user.is_authenticated():
            try:
                convert_tzinfo = Profile.objects.get(user=request.user).timezone or default_tzinfo
            except (Profile.DoesNotExist, AttributeError):
                pass
        request.session["timezone"] = convert_tzinfo
    else:
        convert_tzinfo = request.session["timezone"]

    convert_value = new_value.astimezone(convert_tzinfo)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == "shortdatetime":
        # Check if the date is today
        today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
        if convert_value.toordinal() == today:
            formatted = _lazy(u"Today at %s") % format_time(
                convert_value, format="short", tzinfo=convert_tzinfo, locale=locale
            )
        else:
            formatted = format_datetime(convert_value, format="short", tzinfo=convert_tzinfo, locale=locale)
    elif format == "longdatetime":
        formatted = format_datetime(convert_value, format="long", tzinfo=convert_tzinfo, locale=locale)
    elif format == "date":
        formatted = format_date(convert_value, locale=locale)
    elif format == "time":
        formatted = format_time(convert_value, tzinfo=convert_tzinfo, locale=locale)
    elif format == "datetime":
        formatted = format_datetime(convert_value, tzinfo=convert_tzinfo, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % (convert_value.isoformat(), formatted))
示例#11
0
def test_format_current_moment(monkeypatch):
    import datetime as datetime_module
    frozen_instant = datetime.utcnow()

    class frozen_datetime(datetime):
        @classmethod
        def utcnow(cls):
            return frozen_instant

    # Freeze time! Well, some of it anyway.
    monkeypatch.setattr(datetime_module, "datetime", frozen_datetime)
    assert dates.format_datetime(locale="en_US") == dates.format_datetime(frozen_instant, locale="en_US")
示例#12
0
def matches_datetime_format_for_team(value, tz):
    utcnow = datetime.datetime.utcnow()
    if value.year != utcnow.year:
        return dates.format_datetime(value,
                "MMM d',' yyyy 'at' h':'mm a zzz",
                locale='en_US',
                tzinfo=pytz.timezone(tz))

    return dates.format_datetime(value,
            "EEE',' MMM d 'at' h':'mm a zzz",
            locale='en_US',
            tzinfo=pytz.timezone(tz))
示例#13
0
def test_format_datetime():
    dt = datetime(2007, 4, 1, 15, 30)
    assert (dates.format_datetime(dt, locale='en_US') ==
            u'Apr 1, 2007, 3:30:00 PM')

    full = dates.format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'),
                                 locale='fr_FR')
    assert full == (u'dimanche 1 avril 2007 à 17:30:00 heure '
                    u'd\u2019\xe9t\xe9 d\u2019Europe centrale')
    custom = dates.format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
                                   tzinfo=timezone('US/Eastern'), locale='en')
    assert custom == u'2007.04.01 AD at 11:30:00 EDT'
示例#14
0
文件: helpers.py 项目: FrankBian/kuma
def datetimeformat(context, value, format='shortdatetime', output='html'):
    """
    Returns date/time formatted using babel's locale settings. Uses the
    timezone from settings.py
    """
    if not isinstance(value, datetime.datetime):
        if isinstance(value, datetime.date):
            # Turn a date into a datetime
            value = datetime.datetime.combine(value,
                                              datetime.datetime.min.time())
        else:
            # Expecting datetime value
            raise ValueError

    default_tz = timezone(settings.TIME_ZONE)
    tzvalue = default_tz.localize(value)

    user = context['request'].user
    try:
        profile = user.get_profile()
        if user.is_authenticated() and profile.timezone:
            user_tz = profile.timezone
            tzvalue = user_tz.normalize(tzvalue.astimezone(user_tz))
    except AttributeError:
        pass

    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = _lazy(u'Today at %s') % format_time(
                tzvalue, format='short', locale=locale)
        else:
            formatted = format_datetime(tzvalue, format='short', locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        formatted = format_date(tzvalue, locale=locale)
    elif format == 'time':
        formatted = format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    if output == 'json':
        return formatted
    return jinja2.Markup('<time datetime="%s">%s</time>' %
                         (tzvalue.isoformat(), formatted))
示例#15
0
文件: utils.py 项目: gboone/relate
def format_datetime_local(datetime, format="medium"):
    """Format the output of a datetime object to a localized string"""
    from babel.dates import format_datetime
    from django.conf import settings
    from django.utils.translation.trans_real import to_locale

    # See http://babel.pocoo.org/docs/api/dates/#date-and-time-formatting
    # for customizing the output format.
    try:
        result = format_datetime(datetime, format, locale=to_locale(settings.LANGUAGE_CODE))
    except ValueError:
        result = format_datetime(datetime, format, locale="en_US")

    return result
示例#16
0
文件: home.py 项目: jaesivsm/JARR
def get_article(article_id, parse=False):
    locale = get_locale()
    contr = ArticleController(current_user.id)
    article = contr.get(id=article_id)
    if not article.readed:
        article['readed'] = True
        contr.update({'id': article_id}, {'readed': True})
    article['category_id'] = article.category_id or 0
    feed = FeedController(current_user.id).get(id=article.feed_id)
    article['icon_url'] = url_for('icon.icon', url=feed.icon_url) \
            if feed.icon_url else None
    readability_available = bool(current_user.readability_key
                                 or conf.PLUGINS_READABILITY_KEY)
    article['date'] = format_datetime(localize(article.date), locale=locale)
    article['readability_available'] = readability_available
    if parse or (not article.readability_parsed
            and feed.readability_auto_parse and readability_available):
        try:
            new_content = readability.parse(article.link,
                    current_user.readability_key
                    or conf.PLUGINS_READABILITY_KEY)
        except Exception as error:
            flash("Readability failed with %r" % error, "error")
            article['readability_parsed'] = False
        else:
            article['readability_parsed'] = True
            article['content'] = clean_urls(new_content, article['link'])
            new_attr = {'readability_parsed': True, 'content': new_content}
            contr.update({'id': article['id']}, new_attr)
    return article
示例#17
0
def format_tz(pool, cr, uid, dt, tz=False, format=False, context=None):
    context = dict(context or {})
    if tz:
        context['tz'] = tz or pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] or "UTC"
    timestamp = datetime.datetime.strptime(dt, tools.DEFAULT_SERVER_DATETIME_FORMAT)

    ts = openerp.osv.fields.datetime.context_timestamp(cr, uid, timestamp, context)

    # Babel allows to format datetime in a specific language without change locale
    # So month 1 = January in English, and janvier in French
    # Be aware that the default value for format is 'medium', instead of 'short'
    #     medium:  Jan 5, 2016, 10:20:31 PM |   5 janv. 2016 22:20:31
    #     short:   1/5/16, 10:20 PM         |   5/01/16 22:20
    if context.get('use_babel'):
        # Formatting available here : http://babel.pocoo.org/en/latest/dates.html#date-fields
        from babel.dates import format_datetime
        return format_datetime(ts, format or 'medium', locale=context.get("lang") or 'en_US')

    if format:
        return ts.strftime(format)
    else:
        lang = context.get("lang")
        lang_params = {}
        if lang:
            res_lang = pool.get('res.lang')
            ids = res_lang.search(cr, uid, [("code", "=", lang)])
            if ids:
                lang_params = res_lang.read(cr, uid, ids[0], ["date_format", "time_format"])
        format_date = lang_params.get("date_format", '%B-%d-%Y')
        format_time = lang_params.get("time_format", '%I-%M %p')

        fdate = ts.strftime(format_date).decode('utf-8')
        ftime = ts.strftime(format_time)
        return "%s %s%s" % (fdate, ftime, (' (%s)' % tz) if tz else '')
示例#18
0
def test_smoke_dates(locale):
    locale = Locale.parse(locale)
    instant = datetime.now()
    for width in ("full", "long", "medium", "short"):
        assert dates.format_date(instant, format=width, locale=locale)
        assert dates.format_datetime(instant, format=width, locale=locale)
        assert dates.format_time(instant, format=width, locale=locale)
示例#19
0
def format_tz(env, dt, tz=False, format=False):
    record_user_timestamp = env.user.sudo().with_context(tz=tz or env.user.sudo().tz or 'UTC')
    timestamp = datetime.datetime.strptime(dt, tools.DEFAULT_SERVER_DATETIME_FORMAT)

    ts = fields.Datetime.context_timestamp(record_user_timestamp, timestamp)

    # Babel allows to format datetime in a specific language without change locale
    # So month 1 = January in English, and janvier in French
    # Be aware that the default value for format is 'medium', instead of 'short'
    #     medium:  Jan 5, 2016, 10:20:31 PM |   5 janv. 2016 22:20:31
    #     short:   1/5/16, 10:20 PM         |   5/01/16 22:20
    if env.context.get('use_babel'):
        # Formatting available here : http://babel.pocoo.org/en/latest/dates.html#date-fields
        from babel.dates import format_datetime
        return format_datetime(ts, format or 'medium', locale=env.context.get("lang") or 'en_US')

    if format:
        return pycompat.text_type(ts.strftime(format))
    else:
        lang = env.context.get("lang")
        langs = env['res.lang']
        if lang:
            langs = env['res.lang'].search([("code", "=", lang)])
        format_date = langs.date_format or '%B-%d-%Y'
        format_time = langs.time_format or '%I-%M %p'

        fdate = pycompat.text_type(ts.strftime(format_date))
        ftime = pycompat.text_type(ts.strftime(format_time))
        return u"%s %s%s" % (fdate, ftime, (u' (%s)' % tz) if tz else u'')
示例#20
0
    def get_bar_graph_datas(self):
        data = []
        today = datetime.strptime(fields.Date.context_today(self), DF)
        data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'})
        day_of_week = int(format_datetime(today, 'e', locale=self._context.get(
            'lang') or 'en_US'))
        first_day_of_week = today + timedelta(days=-day_of_week + 1)
        for i in range(-1, 4):
            if i == 0:
                label = _('This Week')
            elif i == 3:
                label = _('Future')
            else:
                start_week = first_day_of_week + timedelta(days=i * 7)
                end_week = start_week + timedelta(days=6)
                if start_week.month == end_week.month:
                    label = \
                        str(start_week.day) + '-' + str(end_week.day) + ' ' + \
                        format_date(end_week, 'MMM',
                                    locale=self._context.get(
                                        'lang') or 'en_US')
                else:
                    label = \
                        format_date(start_week, 'd MMM',
                                    locale=self._context.get('lang') or 'en_US'
                                    ) + '-' + format_date(
                            end_week, 'd MMM',
                            locale=self._context.get('lang') or 'en_US')
            data.append({
                'label': label,
                'value': 0.0,
                'type': 'past' if i < 0 else 'future'})

        select_sql_clause = 'SELECT count(*) FROM helpdesk_ticket AS h ' \
                            'WHERE issue_type_id = %(issue_type_id)s'
        query_args = {'issue_type_id': self.id}
        query = ''
        start_date = (first_day_of_week + timedelta(days=-7))
        for i in range(0, 6):
            if i == 0:
                query += "(" + select_sql_clause + " and start_date < '" + \
                         start_date.strftime(DF) + "')"
            elif i == 5:
                query += " UNION ALL (" + select_sql_clause + \
                         " and start_date >= '" + \
                         start_date.strftime(DF) + "')"
            else:
                next_date = start_date + timedelta(days=7)
                query += " UNION ALL (" + select_sql_clause + \
                         " and start_date >= '" + start_date.strftime(DF) + \
                         "' and end_date < '" + next_date.strftime(DF) + \
                         "')"
                start_date = next_date

        self.env.cr.execute(query, query_args)
        query_results = self.env.cr.dictfetchall()
        for index in range(0, len(query_results)):
            if query_results[index]:
                data[index]['value'] = query_results[index].get('count')
        return [{'values': data}]
示例#21
0
 def test_default(self):
     """Expects shortdatetime."""
     value_test = datetime.fromordinal(733900)
     value_expected = format_datetime(value_test, format='short',
                                      locale=u'en_US')
     value_returned = datetimeformat(self.context, value_test)
     eq_(pq(value_returned)('time').text(), value_expected)
示例#22
0
    def test_format_datetime(self):
        import datetime
        from babel.dates import format_datetime
        from babel.core import UnknownLocaleError

        api = self.make()
        first = datetime.datetime(2012, 1, 1, 0)
        self.assertEqual(api.format_datetime(first), format_datetime(first, format="medium", locale="en"))
        self.assertEqual(
            api.format_datetime(time.mktime(first.timetuple())), format_datetime(first, format="medium", locale="en")
        )
        self.assertEqual(
            api.format_datetime(first, format="short"), format_datetime(first, format="short", locale="en")
        )
        api.locale_name = "unknown"
        self.assertRaises(UnknownLocaleError, api.format_datetime, first)
示例#23
0
    def format_datetime(self, datetime=None, format=None, rebase=True):
        """Returns a date and time formatted according to the given pattern
        and following the current locale and timezone.

        :param datetime:
            A ``datetime`` object. If None, the current date and time in UTC
            is used.
        :param format:
            The format to be returned. Valid values are "short", "medium",
            "long", "full" or a custom date/time pattern. Example outputs:

            - short:  11/10/09 4:36 PM
            - medium: Nov 10, 2009 4:36:05 PM
            - long:   November 10, 2009 4:36:05 PM +0000
            - full:   Tuesday, November 10, 2009 4:36:05 PM World (GMT) Time

        :param rebase:
            If True, converts the datetime to the current :attr:`timezone`.
        :returns:
            A formatted date and time in unicode.
        """
        format = self._get_format('datetime', format)

        kwargs = {}
        if rebase:
            kwargs['tzinfo'] = self.tzinfo

        return dates.format_datetime(datetime, format, locale=self.locale,
                                     **kwargs)
示例#24
0
def when_text(d,t=None):
    """
    Return a string with a concise representation of the given 
    date and time combination.
    Examples:
    
    >>> when_text(datetime.date(2013,12,25))
    u'2013 Dec 25 (Wed)'
    
    >>> when_text(datetime.date(2013,12,25),datetime.time(17,15,00))
    u'2013 Dec 25 (Wed) 17:15'
    
    >>> when_text(None)
    u''
    
    """
    if d is None: return ''
    fmt = 'yyyy MMM dd (EE)'
    if t is None: 
        return format_date(d,fmt,locale=to_locale(translation.get_language()))
    #~ if d.year == datetime.date.today().year:
        #~ fmt = "%a" + settings.SITE.time_format_strftime
    #~ else:
        #~ fmt = "%a %y %b %d" + settings.SITE.time_format_strftime
    #~ fmt = "%a %Y %b %d " + settings.SITE.time_format_strftime
    #~ return datetime.datetime.combine(d,t).strftime(fmt)
    fmt += " HH:mm"
    return format_datetime(datetime.datetime.combine(d,t),fmt,locale=to_locale(translation.get_language()))
示例#25
0
def i_format(loc, s, *a, **kw):
    if a:
        a = list(a)
    for c, f in [(a, enumerate), (kw, dict.items)]:
        for k, o in f(c):
            o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None)
            if isinstance(o, text_type):
                pass
            elif isinstance(o, Decimal):
                c[k] = format_decimal(o, locale=loc)
            elif isinstance(o, int):
                c[k] = format_number(o, locale=loc)
            elif isinstance(o, Money):
                c[k] = loc.format_money(o)
            elif isinstance(o, MoneyBasket):
                c[k] = loc.format_money_basket(o)
            elif isinstance(o, Age):
                c[k] = format_timedelta(o, locale=loc, **o.format_args)
            elif isinstance(o, timedelta):
                c[k] = format_timedelta(o, locale=loc)
            elif isinstance(o, datetime):
                c[k] = format_datetime(o, locale=loc)
            elif isinstance(o, date):
                c[k] = format_date(o, locale=loc)
            elif isinstance(o, Locale):
                c[k] = loc.languages.get(o.language) or o.language.upper()
            elif isinstance(o, Currency):
                c[k] = loc.currencies.get(o, o)
            if wrapper:
                c[k] = wrapper % (c[k],)
    return s.format(*a, **kw)
示例#26
0
    def get_traffic(cls, thing, start, end):
        """Retrieve traffic by interval for a Promoted Link or PromoCampaign."""
        history = get_promo_traffic(thing, start, end)
        interval = cls.get_interval(thing)
        needs_hour_adjustment = _use_adserver_reporting(thing)
        promote_hour = promote.promo_datetime_now().hour

        computed_history = []
        for date, data in history:
            imps = data[0]
            clicks = data[1]
            spent = None if len(data) == 2 else data[2]
            ctr = _clickthrough_rate(imps, clicks)

            # replace hour to ensure that adserver dates appear correct
            # since we store them without the promotion hour.
            if needs_hour_adjustment:
                date = date.replace(hour=promote_hour)

            date = date.replace(tzinfo=pytz.utc)
            date = date.astimezone(pytz.timezone("EST"))
            datestr = format_datetime(
                date,
                locale=c.locale,
                format=cls.date_format_by_interval.get(interval),
            )
            values = ((imps, format_number(imps)), (clicks, format_number(clicks)), (ctr, format_number(ctr)))
            if spent is not None:
                values = ((spent, format_currency(spent, 'USD', locale=c.locale)),) + values
            computed_history.append((date, datestr, values))
        return computed_history
示例#27
0
 def asString(self, objValue, objType):
     '''
     @see: Converter.asString
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if isinstance(objType, TypeModel): # If type model is provided we consider the model property type
         assert isinstance(objType, TypeModel)
         container = objType.container
         assert isinstance(container, Model)
         objType = container.properties[container.propertyId]
     if objType.isOf(str):
         return objValue
     if objType.isOf(bool):
         return str(objValue)
     if objType.isOf(Percentage):
         return bn.format_percent(objValue, self.formats.get(Percentage, None), self.locale)
     if objType.isOf(Number):
         return bn.format_decimal(objValue, self.formats.get(Number, None), self.locale)
     if objType.isOf(Date):
         return bd.format_date(objValue, self.formats.get(Date, None), self.locale)
     if objType.isOf(Time):
         return bd.format_time(objValue, self.formats.get(Time, None), self.locale)
     if objType.isOf(DateTime):
         return bd.format_datetime(objValue, self.formats.get(DateTime, None), None, self.locale)
     raise TypeError('Invalid object type %s for Babel converter' % objType)
示例#28
0
 def test_locale(self):
     """Expects shortdatetime in French."""
     self.context["request"].locale = u"fr"
     value_test = datetime.fromordinal(733900)
     value_expected = format_datetime(value_test, format="short", locale=u"fr")
     value_returned = datetimeformat(self.context, value_test)
     eq_(pq(value_returned)("time").text(), value_expected)
示例#29
0
 def test_longdatetime(self):
     """Expects long format."""
     value_test = datetime.fromordinal(733900)
     tzvalue = timezone(settings.TIME_ZONE).localize(value_test)
     value_expected = format_datetime(tzvalue, format="long", locale=u"en_US")
     value_returned = datetimeformat(self.context, value_test, format="longdatetime")
     eq_(pq(value_returned)("time").text(), value_expected)
def export_user_data(app_user, data_export_email):
    human_user, app_id = get_app_user_tuple(app_user)
    date = format_datetime(datetime.datetime.now(), locale='en', format='yyyy_MM_dd')
    result_path = '/%s/users/%s/%s' % (EXPORTS_BUCKET, app_user.email(), date)

    def update():
        user_data_export_key = UserDataExport.create_key(app_user, date)
        user_data_export = UserDataExport.get(user_data_export_key)
        if user_data_export:
            return user_data_export.data_export_email

        user_data_export = UserDataExport(key=user_data_export_key)
        user_data_export.creation_time = now()
        user_data_export.data_export_email = data_export_email
        user_data_export.put()

        counter = ExportUserPipeline(result_path, human_user.email(), app_id, data_export_email)
        task = counter.start(return_task=True)
        task.add(queue_name=DATA_EXPORT_QUEUE, transactional=True)

        redirect_url = "%s/status?root=%s" % (counter.base_path, counter.pipeline_id)
        logging.info("export pipeline url: %s", redirect_url)
        return None

    return run_in_transaction(update, xg=True)
示例#31
0
 def format_datetime_localized(self, dt):
     """Formats a datetime object to a localized human-readable string based
     on the current locale."""
     return format_datetime(dt, locale=self.__get_env_language_for_babel());
示例#32
0
    def test_extraction_with_default_mapping(self):
        self.cmd.copyright_holder = 'FooBar, Inc.'
        self.cmd.msgid_bugs_address = '*****@*****.**'
        self.cmd.output_file = 'project/i18n/temp.pot'
        self.cmd.add_comments = 'TRANSLATOR:,TRANSLATORS:'

        self.cmd.finalize_options()
        self.cmd.run()

        pot_file = os.path.join(self.datadir, 'project', 'i18n', 'temp.pot')
        assert os.path.isfile(pot_file)

        self.assertEqual(
            r"""# Translations template for TestProject.
# Copyright (C) %(year)s FooBar, Inc.
# This file is distributed under the same license as the TestProject
# project.
# FIRST AUTHOR <EMAIL@ADDRESS>, %(year)s.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: TestProject 0.1\n"
"Report-Msgid-Bugs-To: [email protected]\n"
"POT-Creation-Date: %(date)s\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <*****@*****.**>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel %(version)s\n"

#. TRANSLATOR: This will be a translator coment,
#. that will include several lines
#: project/file1.py:8
msgid "bar"
msgstr ""

#: project/file2.py:9
msgid "foobar"
msgid_plural "foobars"
msgstr[0] ""
msgstr[1] ""

#: project/CVS/this_wont_normally_be_here.py:11
msgid "FooBar"
msgid_plural "FooBars"
msgstr[0] ""
msgstr[1] ""

""" % {
                'version':
                VERSION,
                'year':
                time.strftime('%Y'),
                'date':
                format_datetime(datetime.now(LOCALTZ),
                                'yyyy-MM-dd HH:mmZ',
                                tzinfo=LOCALTZ,
                                locale='en')
            },
            open(pot_file, 'U').read())
示例#33
0
#. that will include several lines
#: project/file1.py:8
msgid "bar"
msgstr ""

#: project/file2.py:9
msgid "foobar"
msgid_plural "foobars"
msgstr[0] ""

""" % {
                'version':
                VERSION,
                'date':
                format_datetime(datetime.now(LOCALTZ),
                                'yyyy-MM-dd HH:mmZ',
                                tzinfo=LOCALTZ,
                                locale='en')
            },
            open(po_file, 'U').read())

    def test_init_more_than_2_plural_forms(self):
        po_file = os.path.join(self.datadir, 'project', 'i18n', 'lv_LV',
                               'LC_MESSAGES', 'messages.po')
        try:
            self.cli.run(sys.argv + [
                'init', '--locale', 'lv_LV', '-d',
                os.path.join(self.datadir, 'project', 'i18n'), '-i',
                os.path.join(self.datadir, 'project', 'i18n', 'messages.pot')
            ])
        except SystemExit, e:
            self.assertEqual(0, e.code)
示例#34
0
 def format_datetime(self,
                     datetime=None,
                     format="medium",
                     tzinfo=None) -> Text:
     """Format datetime according to the locale"""
     return dates.format_datetime(datetime, format, tzinfo, self.lang)
示例#35
0
def _pick_winner(service_user, sln_loyalty_lottery_key):
    now_ = now()
    sln_loyalty_lottery = db.get(sln_loyalty_lottery_key)
    if sln_loyalty_lottery.claimed or sln_loyalty_lottery.redeemed or sln_loyalty_lottery.deleted:
        return
    if sln_loyalty_lottery.schedule_loot_time > 0:
        return
    service_identity = sln_loyalty_lottery.service_identity
    service_identity_user = create_service_identity_user_wo_default(
        service_user, service_identity)
    sls_key = SolutionLoyaltySettings.create_key(service_user)
    slls_key = SolutionLoyaltyLotteryStatistics.create_key(
        service_user, service_identity)
    sln_settings_key = SolutionSettings.create_key(service_user)
    sln_loyalty_settings, slls, sln_settings = db.get(
        [sls_key, slls_key, sln_settings_key])

    if sln_loyalty_settings.loyalty_type != SolutionLoyaltySettings.LOYALTY_TYPE_LOTTERY:
        sln_loyalty_lottery.deleted = True
        sln_loyalty_lottery.put()
        return

    logging.info("loyalty lottery loot: %s", service_user)
    possible_winners = []

    if slls:
        for i, app_user in enumerate(slls.app_users):
            if app_user not in sln_loyalty_lottery.skip_winners and app_user != sln_loyalty_lottery.winner:
                for i in xrange(slls.count[i]):
                    possible_winners.append(app_user)

    logging.debug("possible winners count: %s", len(possible_winners))

    if len(possible_winners) == 0:
        if sln_loyalty_lottery.winner:
            logging.debug("can not assign winner, keep old")
        else:
            logging.debug("can not assign winner, delete lottery")
            sln_loyalty_lottery.deleted = True
            sln_loyalty_lottery.put()
        return

    else:
        winner = random.choice(possible_winners)
        logging.debug("new winner: %s", winner)

    slvl = SolutionLoyaltyVisitLottery.all() \
        .ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) \
        .filter('redeemed =', False) \
        .filter('app_user ='******'t use get_profile_infos
        profile_info = get_profile_infos([slvl.app_user],
                                         allow_none_in_results=True)[0]
        if not profile_info or profile_info.isServiceIdentity:
            azzert(False, "profile_info for app_user %s not found!" % winner)
        else:
            user_detail = UserDetailsTO.fromUserProfile(profile_info)

    loot_datetime_tz = datetime.fromtimestamp(
        sln_loyalty_lottery.end_timestamp,
        pytz.timezone(sln_settings.timezone))
    loot_date_str = format_datetime(loot_datetime_tz,
                                    format='medium',
                                    locale=sln_settings.main_language
                                    or DEFAULT_LANGUAGE)

    next_datetime_tz = datetime.fromtimestamp(
        now() + 24 * 3600, pytz.timezone(sln_settings.timezone))
    next_date_str = format_datetime(next_datetime_tz,
                                    format='medium',
                                    locale=sln_settings.main_language
                                    or DEFAULT_LANGUAGE)

    msg_ok = translate(sln_settings.main_language,
                       SOLUTION_COMMON,
                       'loyalty-lottery-loot-ok',
                       name=user_detail.name,
                       date_loot=loot_date_str,
                       price=sln_loyalty_lottery.winnings,
                       date=next_date_str)
    msg_sorry = translate(sln_settings.main_language, SOLUTION_COMMON,
                          'loyalty-lottery-loot-nok')

    btn = AnswerTO()
    btn.id = u'%s' % json.dumps({"key": unicode(sln_loyalty_lottery_key)})
    btn.type = u'button'
    btn.caption = translate(sln_settings.main_language, SOLUTION_COMMON,
                            'Confirm')
    btn.action = None
    btn.ui_flags = 0

    message_flags = Message.FLAG_ALLOW_DISMISS

    sln_i_settings = get_solution_settings_or_identity_settings(
        sln_settings, service_identity)

    def trans():
        sm_data = []

        if sln_loyalty_lottery.winner_timestamp != 0:
            logging.debug("loyalty lottery loot: update winner %s",
                          sln_loyalty_lottery.winner)
            sim_parent, _ = add_solution_inbox_message(
                service_user,
                sln_loyalty_lottery.solution_inbox_message_key,
                True,
                None,
                now_,
                msg_sorry,
                mark_as_read=True)
            if sim_parent.message_key_by_tag:
                message_key_by_tag = json.loads(sim_parent.message_key_by_tag)
                if message_key_by_tag.get(u"loyalty_lottery_loot", None):
                    deferred.defer(_messaging_seal,
                                   service_user,
                                   message_key_by_tag[u"loyalty_lottery_loot"],
                                   sim_parent.message_key,
                                   sim_parent.message_key,
                                   1,
                                   _transactional=True)

            send_inbox_forwarders_message(
                service_user,
                service_identity,
                None,
                msg_sorry, {
                    'if_name': user_detail.name,
                    'if_email': user_detail.email
                },
                message_key=sim_parent.solution_inbox_message_key,
                reply_enabled=sim_parent.reply_enabled,
                send_reminder=False)

            deferred.defer(send_email_to_user_for_loyalty_update, service_user,
                           service_identity, sln_loyalty_lottery.winner,
                           msg_sorry, False)
            sm_data.append({
                u"type":
                u"solutions.common.messaging.update",
                u"message":
                serialize_complex_value(
                    SolutionInboxMessageTO.fromModel(sim_parent, sln_settings,
                                                     sln_i_settings, True),
                    SolutionInboxMessageTO, False)
            })

        logging.debug("loyalty lottery loot: new winner %s", winner)

        sim_parent = create_solution_inbox_message(
            service_user,
            service_identity,
            SolutionInboxMessage.CATEGORY_LOYALTY,
            unicode(sln_loyalty_lottery_key),
            True, [user_detail],
            now_,
            msg_ok,
            True,
            mark_as_read=True)

        sln_loyalty_lottery.solution_inbox_message_key = sim_parent.solution_inbox_message_key

        if sln_loyalty_lottery.winner:
            if not sln_loyalty_lottery.skip_winners:
                sln_loyalty_lottery.skip_winners = []
            sln_loyalty_lottery.skip_winners.append(sln_loyalty_lottery.winner)
        sln_loyalty_lottery.pending = False
        sln_loyalty_lottery.winner = winner
        sln_loyalty_lottery.winner_info = SolutionUser.fromTO(
            user_detail) if user_detail else None
        sln_loyalty_lottery.winner_timestamp = now_
        sln_loyalty_lottery.put()

        send_inbox_forwarders_message(
            service_user,
            service_identity,
            None,
            msg_ok, {
                'if_name': user_detail.name,
                'if_email': user_detail.email
            },
            message_key=sim_parent.solution_inbox_message_key,
            reply_enabled=sim_parent.reply_enabled,
            send_reminder=False,
            answers=[btn],
            store_tag=u"loyalty_lottery_loot",
            flags=message_flags)

        deferred.defer(send_email_to_user_for_loyalty_update, service_user,
                       service_identity, sln_loyalty_lottery.winner, msg_ok,
                       False, sim_parent.solution_inbox_message_key)
        sm_data.append({
            u"type":
            u"solutions.common.messaging.update",
            u"message":
            serialize_complex_value(
                SolutionInboxMessageTO.fromModel(sim_parent, sln_settings,
                                                 sln_i_settings, True),
                SolutionInboxMessageTO, False)
        })
        sm_data.append({u"type": u"solutions.common.loyalty.lottery.update"})
        send_message(service_user, sm_data, service_identity=service_identity)

        deferred.defer(_continue,
                       service_user,
                       service_identity,
                       sln_loyalty_lottery_key,
                       _transactional=True)

    xg_on = db.create_transaction_options(xg=True)
    db.run_in_transaction_options(xg_on, trans)
    def get_bar_graph_datas(self):
        data = []
        today = fields.Datetime.now(self)
        data.append({'label': _('Due'), 'value': 0.0, 'type': 'past'})
        day_of_week = int(
            format_datetime(today, 'e', locale=get_lang(self.env).code))
        first_day_of_week = today + timedelta(days=-day_of_week + 1)
        for i in range(-1, 4):
            if i == 0:
                label = _('This Week')
            elif i == 3:
                label = _('Not Due')
            else:
                start_week = first_day_of_week + timedelta(days=i * 7)
                end_week = start_week + timedelta(days=6)
                if start_week.month == end_week.month:
                    label = str(start_week.day) + '-' + str(
                        end_week.day) + ' ' + format_date(
                            end_week, 'MMM', locale=get_lang(self.env).code)
                else:
                    label = format_date(
                        start_week, 'd MMM',
                        locale=get_lang(self.env).code) + '-' + format_date(
                            end_week, 'd MMM', locale=get_lang(self.env).code)
            data.append({
                'label': label,
                'value': 0.0,
                'type': 'past' if i < 0 else 'future'
            })

        # Build SQL query to find amount aggregated by week
        (select_sql_clause, query_args) = self._get_bar_graph_select_query()
        query = ''
        start_date = (first_day_of_week + timedelta(days=-7))
        for i in range(0, 6):
            if i == 0:
                query += "(" + select_sql_clause + " and invoice_date_due < '" + start_date.strftime(
                    DF) + "')"
            elif i == 5:
                query += " UNION ALL (" + select_sql_clause + " and invoice_date_due >= '" + start_date.strftime(
                    DF) + "')"
            else:
                next_date = start_date + timedelta(days=7)
                query += " UNION ALL (" + select_sql_clause + " and invoice_date_due >= '" + start_date.strftime(
                    DF) + "' and invoice_date_due < '" + next_date.strftime(
                        DF) + "')"
                start_date = next_date

        self.env.cr.execute(query, query_args)
        query_results = self.env.cr.dictfetchall()
        is_sample_data = True
        for index in range(0, len(query_results)):
            if query_results[index].get('aggr_date') != None:
                is_sample_data = False
                data[index]['value'] = query_results[index].get('total')

        [graph_title, graph_key] = self._graph_title_and_key()

        if is_sample_data:
            for index in range(0, len(query_results)):
                data[index]['type'] = 'o_sample_data'
                # we use unrealistic values for the sample data
                data[index]['value'] = random.randint(0, 20)
                graph_key = _('Sample data')

        return [{
            'values': data,
            'title': graph_title,
            'key': graph_key,
            'is_sample_data': is_sample_data
        }]
示例#37
0
文件: util.py 项目: timgates42/Kotti
 def format_datetime(self, dt, fmt=None):
     if fmt is None:
         fmt = self.S["kotti.datetime_format"]
     if not isinstance(dt, datetime):
         dt = datetime.fromtimestamp(dt)
     return format_datetime(dt, format=fmt, locale=self.locale_name)
示例#38
0
def datetimeformat(context, value, format="shortdatetime"):
    """
    Returns a formatted date/time using Babel's locale settings. Uses the
    timezone from settings.py, if the user has not been authenticated.
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError(
            "Unexpected value {value} passed to datetimeformat".format(
                value=value))

    request = context.get("request")

    default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
    if value.tzinfo is None:
        value = default_tzinfo.localize(value)
        new_value = value.astimezone(default_tzinfo)
    else:
        new_value = value

    if hasattr(request, "session"):
        if "timezone" not in request.session:
            if hasattr(request, "user") and request.user.is_authenticated:
                try:
                    convert_tzinfo = (
                        Profile.objects.get(user=request.user).timezone
                        or default_tzinfo)
                except (Profile.DoesNotExist, AttributeError):
                    pass
            request.session["timezone"] = convert_tzinfo
        else:
            convert_tzinfo = request.session["timezone"] or default_tzinfo

    convert_value = new_value.astimezone(convert_tzinfo)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == "shortdatetime":
        # Check if the date is today
        today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
        if convert_value.toordinal() == today:
            formatted = _lazy("Today at %s") % format_time(
                convert_value,
                format="short",
                tzinfo=convert_tzinfo,
                locale=locale)
        else:
            formatted = format_datetime(convert_value,
                                        format="short",
                                        tzinfo=convert_tzinfo,
                                        locale=locale)
    elif format == "longdatetime":
        formatted = format_datetime(convert_value,
                                    format="long",
                                    tzinfo=convert_tzinfo,
                                    locale=locale)
    elif format == "date":
        formatted = format_date(convert_value, locale=locale)
    elif format == "time":
        formatted = format_time(convert_value,
                                tzinfo=convert_tzinfo,
                                locale=locale)
    elif format == "datetime":
        formatted = format_datetime(convert_value,
                                    tzinfo=convert_tzinfo,
                                    locale=locale)
    elif format == "year":
        formatted = format_datetime(convert_value,
                                    format="yyyy",
                                    tzinfo=convert_tzinfo,
                                    locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' %
                         (convert_value.isoformat(), formatted))
示例#39
0
文件: builder.py 项目: marcw/rstblog
 def format_datetime(self, datetime=None, format='medium'):
     return dates.format_datetime(datetime, format, locale=self.locale)
示例#40
0
    def get_bar_graph_datas(self):
        data = []
        today = datetime.strptime(fields.Date.context_today(self), DF)
        data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'})
        day_of_week = int(
            format_datetime(today,
                            'e',
                            locale=self._context.get('lang', 'en_US')))
        first_day_of_week = today + timedelta(days=-day_of_week + 1)
        for i in range(-1, 4):
            if i == 0:
                label = _('This Week')
            elif i == 3:
                label = _('Future')
            else:
                start_week = first_day_of_week + timedelta(days=i * 7)
                end_week = start_week + timedelta(days=6)
                if start_week.month == end_week.month:
                    label = str(start_week.day) + '-' + str(
                        end_week.day) + ' ' + format_date(
                            end_week,
                            'MMM',
                            locale=self._context.get('lang', 'en_US'))
                else:
                    label = format_date(
                        start_week,
                        'd MMM',
                        locale=self._context.get(
                            'lang', 'en_US')) + '-' + format_date(
                                end_week,
                                'd MMM',
                                locale=self._context.get('lang', 'en_US'))
            data.append({
                'label': label,
                'value': 0.0,
                'type': 'past' if i < 0 else 'future'
            })

        # Build SQL query to find amount aggregated by week
        select_sql_clause = """SELECT sum(residual_company_signed) as total, min(date) as aggr_date from account_invoice where journal_id = %(journal_id)s and state = 'open'"""
        query = ''
        start_date = (first_day_of_week + timedelta(days=-7))
        for i in range(0, 6):
            if i == 0:
                query += "(" + select_sql_clause + " and date < '" + start_date.strftime(
                    DF) + "')"
            elif i == 6:
                query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime(
                    DF) + "')"
            else:
                next_date = start_date + timedelta(days=7)
                query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime(
                    DF) + "' and date < '" + next_date.strftime(DF) + "')"
                start_date = next_date

        self.env.cr.execute(query, {'journal_id': self.id})
        query_results = self.env.cr.dictfetchall()
        for index in range(0, len(query_results)):
            if query_results[index].get('aggr_date') != None:
                data[index]['value'] = query_results[index].get('total')

        return [{'values': data}]
示例#41
0
def fmt_datetime(value, format='short'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'short':
        format="dd.MM.yyyy"
    return format_datetime(value, format)
示例#42
0
 def test_timezone_formats(self):
     dt = datetime(2016, 1, 13, 7, 8, 35)
     tz = dates.get_timezone('America/Los_Angeles')
     dt = tz.localize(dt)
     formatted_string = dates.format_datetime(dt, 'z', locale='en')
     self.assertEqual(u'PST', formatted_string)
     formatted_string = dates.format_datetime(dt, 'zz', locale='en')
     self.assertEqual(u'PST', formatted_string)
     formatted_string = dates.format_datetime(dt, 'zzz', locale='en')
     self.assertEqual(u'PST', formatted_string)
     formatted_string = dates.format_datetime(dt, 'zzzz', locale='en')
     self.assertEqual(u'Pacific Standard Time', formatted_string)
     formatted_string = dates.format_datetime(dt, 'Z', locale='en')
     self.assertEqual(u'-0800', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZ', locale='en')
     self.assertEqual(u'-0800', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZ', locale='en')
     self.assertEqual(u'-0800', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en')
     self.assertEqual(u'GMT-08:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en')
     self.assertEqual(u'-08:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'OOOO', locale='en')
     self.assertEqual(u'GMT-08:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'VV', locale='en')
     self.assertEqual(u'America/Los_Angeles', formatted_string)
     formatted_string = dates.format_datetime(dt, 'VVV', locale='en')
     self.assertEqual(u'Los Angeles', formatted_string)
     formatted_string = dates.format_datetime(dt, 'X', locale='en')
     self.assertEqual(u'-08', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XX', locale='en')
     self.assertEqual(u'-0800', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXX', locale='en')
     self.assertEqual(u'-08:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXXX', locale='en')
     self.assertEqual(u'-0800', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en')
     self.assertEqual(u'-08:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'x', locale='en')
     self.assertEqual(u'-08', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xx', locale='en')
     self.assertEqual(u'-0800', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxx', locale='en')
     self.assertEqual(u'-08:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxxx', locale='en')
     self.assertEqual(u'-0800', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en')
     self.assertEqual(u'-08:00', formatted_string)
     dt = datetime(2016, 1, 13, 7, 8, 35)
     tz = dates.get_timezone('UTC')
     dt = tz.localize(dt)
     formatted_string = dates.format_datetime(dt, 'Z', locale='en')
     self.assertEqual(u'+0000', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZ', locale='en')
     self.assertEqual(u'+0000', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZ', locale='en')
     self.assertEqual(u'+0000', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en')
     self.assertEqual(u'GMT+00:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en')
     self.assertEqual(u'Z', formatted_string)
     formatted_string = dates.format_datetime(dt, 'OOOO', locale='en')
     self.assertEqual(u'GMT+00:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'VV', locale='en')
     self.assertEqual(u'Etc/UTC', formatted_string)
     formatted_string = dates.format_datetime(dt, 'VVV', locale='en')
     self.assertEqual(u'UTC', formatted_string)
     formatted_string = dates.format_datetime(dt, 'X', locale='en')
     self.assertEqual(u'Z', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XX', locale='en')
     self.assertEqual(u'Z', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXX', locale='en')
     self.assertEqual(u'Z', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXXX', locale='en')
     self.assertEqual(u'Z', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en')
     self.assertEqual(u'Z', formatted_string)
     formatted_string = dates.format_datetime(dt, 'x', locale='en')
     self.assertEqual(u'+00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xx', locale='en')
     self.assertEqual(u'+0000', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxx', locale='en')
     self.assertEqual(u'+00:00', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxxx', locale='en')
     self.assertEqual(u'+0000', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en')
     self.assertEqual(u'+00:00', formatted_string)
     dt = datetime(2016, 1, 13, 7, 8, 35)
     tz = dates.get_timezone('Asia/Kolkata')
     dt = tz.localize(dt)
     formatted_string = dates.format_datetime(dt, 'zzzz', locale='en')
     self.assertEqual(u'India Standard Time', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en')
     self.assertEqual(u'GMT+05:30', formatted_string)
     formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en')
     self.assertEqual(u'+05:30', formatted_string)
     formatted_string = dates.format_datetime(dt, 'OOOO', locale='en')
     self.assertEqual(u'GMT+05:30', formatted_string)
     formatted_string = dates.format_datetime(dt, 'VV', locale='en')
     self.assertEqual(u'Asia/Calcutta', formatted_string)
     formatted_string = dates.format_datetime(dt, 'VVV', locale='en')
     self.assertEqual(u'Kolkata', formatted_string)
     formatted_string = dates.format_datetime(dt, 'X', locale='en')
     self.assertEqual(u'+0530', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XX', locale='en')
     self.assertEqual(u'+0530', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXX', locale='en')
     self.assertEqual(u'+05:30', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXXX', locale='en')
     self.assertEqual(u'+0530', formatted_string)
     formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en')
     self.assertEqual(u'+05:30', formatted_string)
     formatted_string = dates.format_datetime(dt, 'x', locale='en')
     self.assertEqual(u'+0530', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xx', locale='en')
     self.assertEqual(u'+0530', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxx', locale='en')
     self.assertEqual(u'+05:30', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxxx', locale='en')
     self.assertEqual(u'+0530', formatted_string)
     formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en')
     self.assertEqual(u'+05:30', formatted_string)
示例#43
0
 def __get_RFC1123_date(self):
     now = datetime.datetime.utcnow()
     return format_datetime(now, self.__RFC1123_FORMAT, locale='en') \
         + ' GMT'
示例#44
0
def generateDocXReport(month_id, year, lang, film_id):
    langMap = dict(fr={
        'template': 'template-fr.docx',
        'locale': 'fr_FR',
        'emptyList': 'Pas Encore.'
    },
                   en={
                       'template': 'template-en.docx',
                       'locale': 'en_US',
                       'emptyList': 'Not yet.'
                   })

    locale.setlocale(locale.LC_TIME, langMap.get(lang).get('locale'))

    file_path = os.path.join(MEDIA_ROOT, 'reportTemplate/')
    currentFilm = Film.objects.get(id=film_id)
    subList = Submission.objects.filter(dateSubmission__year=year).filter(
        dateSubmission__month=month_id).filter(film_id=film_id)

    selectList = Submission.objects.filter(responseDate__year=year).filter(
        responseDate__month=month_id).filter(film_id=film_id).filter(
            response__iexact='SELECTIONED')
    rejectList = Submission.objects.filter(responseDate__year=year).filter(
        responseDate__month=month_id).filter(film_id=film_id).filter(
            response__iexact='REFUSED')

    subOutput, selectOutput, rejectOutput = [], [], []

    for item in subList:
        subOutput.append({'festival': model_to_dict(item.festival)})
    if not subOutput:
        subOutput.append({'festival': {'name': langMap[lang]['emptyList']}})

    for item in selectList:
        selectOutput.append({'festival': model_to_dict(item.festival)})
    if not subOutput:
        selectOutput.append({'festival': {'name': langMap[lang]['emptyList']}})

    for item in rejectList:
        rejectOutput.append({'festival': model_to_dict(item.festival)})
    if not subOutput:
        rejectOutput.append({'festival': {'name': langMap[lang]['emptyList']}})

    document = DocxTemplate(file_path + langMap[lang]['template'])

    dic = {
        'INSCRIPTIONS_LIST':
        subOutput,
        'MOVIE_NAME':
        currentFilm.name.upper(),
        'CURRENT_DATE':
        format_datetime(date.today(),
                        format='dd MMMM YYYY',
                        locale=langMap[lang]['locale']),
        'TARGET_MONTH':
        format_datetime(datetime.datetime(1900, int(month_id), 1),
                        format='MMMM',
                        locale=langMap[lang]['locale']),
        'TARGET_YEAR':
        str(year),
        'SELECTIONS_LIST':
        selectOutput,
        'REJECTIONS_LIST':
        rejectOutput,
        'PROJECTIONS_LIST':
        langMap[lang]['emptyList']
    }
    document.render(dic)

    document.core_properties.title = currentFilm.name + "-" + lang
    return document
示例#45
0
def generate_prospect_export_excel(prospect_ids, do_send_email=True, recipients=None):
    if not prospect_ids:
        raise BusinessException('No prospects to export')
    azzert(not do_send_email or recipients)
    bold_style = xlwt.XFStyle()
    bold_style.font.bold = True
    column_name, column_address, column_city, column_phone, column_status, column_type, column_categories, column_comments = range(8)

    book = xlwt.Workbook(encoding="utf-8")
    sheet = book.add_sheet('Prospects')
    prospects = Prospect.get(map(Prospect.create_key, prospect_ids))
    app_id = None

    sheet.write(0, column_name, 'Name', bold_style)
    sheet.write(0, column_address, 'Address', bold_style)
    sheet.write(0, column_city, 'City', bold_style)
    sheet.write(0, column_phone, 'Phone', bold_style)
    sheet.write(0, column_status, 'Status', bold_style)
    sheet.write(0, column_type, 'Type', bold_style)
    sheet.write(0, column_categories, 'Category', bold_style)
    sheet.write(0, column_comments, 'Comments', bold_style)
    for i, prospect in enumerate(prospects):
        row = i + 1
        comments_str = '\n'.join(['* %s' % comment.text for comment in prospect.comments])
        sheet.write(row, column_name, prospect.name)
        formatted_address = format_address(prospect.address)
        sheet.write(row, column_address, formatted_address[0])
        sheet.write(row, column_city, formatted_address[1])
        sheet.write(row, column_phone, prospect.phone)
        sheet.write(row, column_status, Prospect.STATUS_TYPES[prospect.status])
        sheet.write(row, column_type, ', '.join(prospect.type))
        sheet.write(row, column_categories, ', '.join(prospect.categories))
        sheet.write(row, column_comments, comments_str)
        sheet.col(column_name).width = 5000
        sheet.col(column_address).width = 5000
        sheet.col(column_phone).width = 5000
        sheet.col(column_status).width = 5000
        sheet.col(column_type).width = 10000
        sheet.col(column_categories).width = 10000
        sheet.col(column_comments).width = 20000
        if not app_id:
            app_id = prospect.app_id
    excel = StringIO()
    book.save(excel)
    excel_string = excel.getvalue()

    if do_send_email:
        app = get_app_by_id(app_id)
        solution_server_settings = get_solution_server_settings()
        current_date = format_datetime(datetime.datetime.now(), locale=DEFAULT_LANGUAGE)
        subject = 'Exported prospects of %s %s' % (app.name, current_date)
        from_email = solution_server_settings.shop_export_email
        to_emails = recipients
        body_text = 'See attachment for the exported prospects'
        
        attachments = []
        attachments.append(('Prospects %s %s.xls' % (app.name, current_date),
                            base64.b64encode(excel_string)))
        
        send_mail(from_email, to_emails, subject, body_text, attachments=attachments)
    return excel_string
示例#46
0
def convert_datetime(dt):
    return dates.format_datetime(dt)
示例#47
0
 def get_datetime_formatted_str(self, ts):
     """return given timestamp as formated datetime string using locale"""
     my_datetime = self.get_datetime_from_ts(ts)
     return format_datetime(my_datetime, format="short", locale=self.locale)
示例#48
0
 def test_with_float(self):
     d = datetime(2012, 4, 1, 15, 30, 29, tzinfo=timezone('UTC'))
     epoch = float(calendar.timegm(d.timetuple()))
     formatted_string = dates.format_datetime(epoch, format='long', locale='en_US')
     self.assertEqual(u'April 1, 2012 at 3:30:29 PM UTC', formatted_string)
示例#49
0
def from_python(field, value):
    """Will return the serialised version of the value the given field
    and value.

    :field: :class:`.Field` instance
    :value: Python value
    :returns: Serialized version.

    """
    serialized = ""
    locale = field._form._locale
    ftype = field.get_type()
    try:
        if value is None:
            serialized = u""
        elif isinstance(value, basestring):
            # Special handling for multiple values (multiselect in
            # checkboxes eg.) which has be converted into a string by
            # SQLAalchemy automatically. eg the python value "['1',
            # '2']" will be converted into the _string_ "{1,2,''}". In
            # this case we need to convert the value back into a list.
            if value.startswith("{") and value.endswith("}"):
                serialized = []
                for v in value.strip("{").strip("}").split(","):
                    serialized.append(from_python(field, v))
            else:
                serialized = unicode(value)
        elif isinstance(value, list):
            vl = []
            for v in value:
                try:
                    vl.append(v.id)
                except AttributeError:
                    vl.append(v)
            serialized = vl
        else:
            try:
                serialized = value.id
            except AttributeError:
                if ftype == "time":
                    td = datetime.timedelta(seconds=int(value))
                    serialized = from_timedelta(td)
                elif ftype == "interval":
                    serialized = from_timedelta(value)
                elif ftype == "datetime":
                    value = get_local_datetime(value)
                    if locale == "de":
                        dateformat = "dd.MM.yyyy HH:mm:ss"
                    else:
                        dateformat = "yyyy-MM-dd HH:mm:ss"
                    serialized = format_datetime(value, format=dateformat)
                elif ftype == "date":
                    if locale == "de":
                        dateformat = "dd.MM.yyyy"
                    else:
                        dateformat = "yyyy-MM-dd"
                    serialized = format_date(value, format=dateformat)
                else:
                    serialized = value
    except AttributeError:
        log.warning('Can not get value for field "%s". '
                    'The field is no attribute of the item' % field.name)
    return serialized
示例#50
0
 def format_datetime_str(self, my_datetime):
     """returns formated datetime string for given dt using locale"""
     return format_datetime(my_datetime, format="short", locale=self.locale)
示例#51
0
 def td_format(self, content):
     try:
         return format_datetime(
             dateutil.parser.parse(content).replace(microsecond=0), 'short')
     except:
         return ''
示例#52
0
 def formated_date(self):
     return format_datetime(self.start_time,
                            format=u"d MMM yyyy à HH:MM",
                            locale="fr_CA")
示例#53
0
    def get_bar_graph_datas(self):
        data = []
        today = datetime.strptime(fields.Date.context_today(self), DF)
        data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'})
        day_of_week = int(
            format_datetime(today,
                            'e',
                            locale=self._context.get('lang') or 'en_US'))
        first_day_of_week = today + timedelta(days=-day_of_week + 1)
        for i in range(-1, 4):
            if i == 0:
                label = _('This Week')
            elif i == 3:
                label = _('Future')
            else:
                start_week = first_day_of_week + timedelta(days=i * 7)
                end_week = start_week + timedelta(days=6)
                if start_week.month == end_week.month:
                    label = str(start_week.day) + '-' + str(
                        end_week.day) + ' ' + format_date(
                            end_week,
                            'MMM',
                            locale=self._context.get('lang') or 'en_US')
                else:
                    label = format_date(start_week,
                                        'd MMM',
                                        locale=self._context.get('lang')
                                        or 'en_US') + '-' + format_date(
                                            end_week,
                                            'd MMM',
                                            locale=self._context.get('lang')
                                            or 'en_US')
            data.append({
                'label': label,
                'value': 0.0,
                'type': 'past' if i < 0 else 'future'
            })

        # Build SQL query to find amount aggregated by week
        (select_sql_clause, query_args) = self._get_bar_graph_select_query()
        query = ''
        start_date = (first_day_of_week + timedelta(days=-7))
        for i in range(0, 6):
            if i == 0:
                query += "(" + select_sql_clause + " and date < '" + start_date.strftime(
                    DF) + "')"
            elif i == 5:
                query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime(
                    DF) + "')"
            else:
                next_date = start_date + timedelta(days=7)
                query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime(
                    DF) + "' and date < '" + next_date.strftime(DF) + "')"
                start_date = next_date

        self.env.cr.execute(query, query_args)
        query_results = self.env.cr.dictfetchall()
        for index in range(0, len(query_results)):
            if query_results[index].get('aggr_date') != None:
                data[index]['value'] = query_results[index].get('total')

        [graph_title, graph_key] = self._graph_title_and_key()
        return [{'values': data, 'title': graph_title, 'key': graph_key}]
示例#54
0
    def _nightly_available_updates(self, request_method, locale):
        tz = datetime.timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone)
        if request_method == "GET":
            repository_url = _REPOSITORY_API_URL
            status, commit = self._load_remote_data(repository_url + '/git/refs/heads/master')
            parents = []
            if status['message'] != '':
                return json.dumps(status)
            if 'object' not in commit:
                status['message'] = _(u'Unexpected data while reading update information')
                return json.dumps(status)

            if commit['object']['sha'] == status['current_commit_hash']:
                status.update({
                    'update': False,
                    'success': True,
                    'message': _(u'No update available. You already have the latest version installed')
                })
                return json.dumps(status)

            # a new update is available
            status['update'] = True

            try:
                headers = {'Accept': 'application/vnd.github.v3+json'}
                r = requests.get(repository_url + '/git/commits/' + commit['object']['sha'], headers=headers)
                r.raise_for_status()
                update_data = r.json()
            except requests.exceptions.HTTPError as e:
                status['error'] = _(u'HTTP Error') + ' ' + str(e)
            except requests.exceptions.ConnectionError:
                status['error'] = _(u'Connection error')
            except requests.exceptions.Timeout:
                status['error'] = _(u'Timeout while establishing connection')
            except requests.exceptions.RequestException:
                status['error'] = _(u'General error')

            if status['message'] != '':
                return json.dumps(status)

            if 'committer' in update_data and 'message' in update_data:
                status['success'] = True
                status['message'] = _(
                    u'A new update is available. Click on the button below to update to the latest version.')

                new_commit_date = datetime.datetime.strptime(
                    update_data['committer']['date'], '%Y-%m-%dT%H:%M:%SZ') - tz
                parents.append(
                    [
                        format_datetime(new_commit_date, format='short', locale=locale),
                        update_data['message'],
                        update_data['sha']
                    ]
                )

                # it only makes sense to analyze the parents if we know the current commit hash
                if status['current_commit_hash'] != '':
                    try:
                        parent_commit = update_data['parents'][0]
                        # limit the maximum search depth
                        remaining_parents_cnt = 10
                    except IndexError:
                        remaining_parents_cnt = None

                    if remaining_parents_cnt is not None:
                        while True:
                            if remaining_parents_cnt == 0:
                                break

                            # check if we are more than one update behind if so, go up the tree
                            if parent_commit['sha'] != status['current_commit_hash']:
                                try:
                                    headers = {'Accept': 'application/vnd.github.v3+json'}
                                    r = requests.get(parent_commit['url'], headers=headers)
                                    r.raise_for_status()
                                    parent_data = r.json()

                                    parent_commit_date = datetime.datetime.strptime(
                                        parent_data['committer']['date'], '%Y-%m-%dT%H:%M:%SZ') - tz
                                    parent_commit_date = format_datetime(
                                        parent_commit_date, format='short', locale=locale)

                                    parents.append([parent_commit_date,
                                                    parent_data['message'].replace('\r\n', '<p>').replace('\n', '<p>')])
                                    parent_commit = parent_data['parents'][0]
                                    remaining_parents_cnt -= 1
                                except Exception:
                                    # it isn't crucial if we can't get information about the parent
                                    break
                            else:
                                # parent is our current version
                                break
                status['history'] = parents[::-1]
            else:
                status['success'] = False
                status['message'] = _(u'Could not fetch update information')
            return json.dumps(status)
        return ''
示例#55
0
文件: views.py 项目: saadow123/1
    def get(self, request, course_id, error=None):
        """Displays the course mode choice page.

        Args:
            request (`Request`): The Django Request object.
            course_id (unicode): The slash-separated course key.

        Keyword Args:
            error (unicode): If provided, display this error message
                on the page.

        Returns:
            Response

        """
        course_key = CourseKey.from_string(course_id)

        # Check whether the user has access to this course
        # based on country access rules.
        embargo_redirect = embargo_api.redirect_if_blocked(
            course_key,
            user=request.user,
            ip_address=get_ip(request),
            url=request.path)
        if embargo_redirect:
            return redirect(embargo_redirect)

        enrollment_mode, is_active = CourseEnrollment.enrollment_mode_for_user(
            request.user, course_key)

        increment('track-selection.{}.{}'.format(
            enrollment_mode, 'active' if is_active else 'inactive'))
        increment('track-selection.views')

        if enrollment_mode is None:
            LOG.info(
                'Rendering track selection for unenrolled user, referred by %s',
                request.META.get('HTTP_REFERER'))

        modes = CourseMode.modes_for_course_dict(course_key)
        ecommerce_service = EcommerceService()

        # We assume that, if 'professional' is one of the modes, it should be the *only* mode.
        # If there are both modes, default to non-id-professional.
        has_enrolled_professional = (
            CourseMode.is_professional_slug(enrollment_mode) and is_active)
        if CourseMode.has_professional_mode(
                modes) and not has_enrolled_professional:
            purchase_workflow = request.GET.get("purchase_workflow", "single")
            verify_url = reverse(
                'verify_student_start_flow',
                kwargs={'course_id': six.text_type(course_key)})
            redirect_url = "{url}?purchase_workflow={workflow}".format(
                url=verify_url, workflow=purchase_workflow)
            if ecommerce_service.is_enabled(request.user):
                professional_mode = modes.get(
                    CourseMode.NO_ID_PROFESSIONAL_MODE) or modes.get(
                        CourseMode.PROFESSIONAL)
                if purchase_workflow == "single" and professional_mode.sku:
                    redirect_url = ecommerce_service.get_checkout_page_url(
                        professional_mode.sku)
                if purchase_workflow == "bulk" and professional_mode.bulk_sku:
                    redirect_url = ecommerce_service.get_checkout_page_url(
                        professional_mode.bulk_sku)
            return redirect(redirect_url)

        course = modulestore().get_course(course_key)

        # If there isn't a verified mode available, then there's nothing
        # to do on this page.  Send the user to the dashboard.
        if not CourseMode.has_verified_mode(modes):
            return redirect(reverse('dashboard'))

        # If a user has already paid, redirect them to the dashboard.
        if is_active and (enrollment_mode in CourseMode.VERIFIED_MODES +
                          [CourseMode.NO_ID_PROFESSIONAL_MODE]):
            # If the course has started redirect to course home instead
            if course.has_started():
                return redirect(
                    reverse('openedx.course_experience.course_home',
                            kwargs={'course_id': course_key}))
            return redirect(reverse('dashboard'))

        donation_for_course = request.session.get("donation_for_course", {})
        chosen_price = donation_for_course.get(six.text_type(course_key), None)

        if CourseEnrollment.is_enrollment_closed(request.user, course):
            locale = to_locale(get_language())
            enrollment_end_date = format_datetime(course.enrollment_end,
                                                  'short',
                                                  locale=locale)
            params = six.moves.urllib.parse.urlencode(
                {'course_closed': enrollment_end_date})
            return redirect('{0}?{1}'.format(reverse('dashboard'), params))

        # When a credit mode is available, students will be given the option
        # to upgrade from a verified mode to a credit mode at the end of the course.
        # This allows students who have completed photo verification to be eligible
        # for university credit.
        # Since credit isn't one of the selectable options on the track selection page,
        # we need to check *all* available course modes in order to determine whether
        # a credit mode is available.  If so, then we show slightly different messaging
        # for the verified track.
        has_credit_upsell = any(
            CourseMode.is_credit_mode(mode)
            for mode in CourseMode.modes_for_course(course_key,
                                                    only_selectable=False))
        course_id = text_type(course_key)

        context = {
            "course_modes_choose_url":
            reverse("course_modes_choose", kwargs={'course_id': course_id}),
            "modes":
            modes,
            "has_credit_upsell":
            has_credit_upsell,
            "course_name":
            course.display_name_with_default,
            "course_org":
            course.display_org_with_default,
            "course_num":
            course.display_number_with_default,
            "chosen_price":
            chosen_price,
            "error":
            error,
            "responsive":
            True,
            "nav_hidden":
            True,
            "content_gating_enabled":
            ContentTypeGatingConfig.enabled_for_enrollment(
                user=request.user, course_key=course_key),
            "course_duration_limit_enabled":
            CourseDurationLimitConfig.enabled_for_enrollment(
                user=request.user, course_key=course_key),
        }
        context.update(
            get_experiment_user_metadata_context(
                course,
                request.user,
            ))

        title_content = ''
        if enrollment_mode:
            title_content = _(
                "Congratulations!  You are now enrolled in {course_name}"
            ).format(course_name=course.display_name_with_default)

        context["title_content"] = title_content

        if "verified" in modes:
            verified_mode = modes["verified"]
            context["suggested_prices"] = [
                decimal.Decimal(x.strip())
                for x in verified_mode.suggested_prices.split(",")
                if x.strip()
            ]
            price_before_discount = verified_mode.min_price

            context["currency"] = verified_mode.currency.upper()
            context["currency_symbol"] = get_currency_symbol(
                verified_mode.currency.upper())
            context["min_price"] = price_before_discount
            context["verified_name"] = verified_mode.name
            context["verified_description"] = verified_mode.description

            if verified_mode.sku:
                context[
                    "use_ecommerce_payment_flow"] = ecommerce_service.is_enabled(
                        request.user)
                context[
                    "ecommerce_payment_page"] = ecommerce_service.payment_page_url(
                    )
                context["sku"] = verified_mode.sku
                context["bulk_sku"] = verified_mode.bulk_sku

        context['currency_data'] = []
        if waffle.switch_is_active('local_currency'):
            if 'edx-price-l10n' not in request.COOKIES:
                currency_data = get_currency_data()
                try:
                    context['currency_data'] = json.dumps(currency_data)
                except TypeError:
                    pass
        return render_to_response("course_modes/choose.html", context)
示例#56
0
 def format_datetime(self, *a):
     return format_datetime(*a, locale=self)
示例#57
0
    def _mails(self, users_and_watches):
        """Send one kind of mail to the asker and another to other watchers."""
        # Cache answer.question, similar to caching solution.question below.
        self.answer.question = self.instance
        asker_id = self.answer.question.creator.id

        c = {
            'answer': self.answer.content,
            'answer_html': self.answer.content_parsed,
            'answerer': self.answer.creator,
            'question_title': self.instance.title,
            'host': Site.objects.get_current().domain
        }

        @email_utils.safe_translation
        def _make_mail(locale, user, context):
            # Avoid circular import issues
            from kitsune.users.helpers import display_name

            is_asker = asker_id == user.id
            if is_asker:
                subject = _(
                    u'%s posted an answer to your question "%s"' %
                    (display_name(self.answer.creator), self.instance.title))
                text_template = 'questions/email/new_answer_to_asker.ltxt'
                html_template = 'questions/email/new_answer_to_asker.html'
            else:
                subject = _(u'Re: %s' % self.instance.title)
                text_template = 'questions/email/new_answer.ltxt'
                html_template = 'questions/email/new_answer.html'

            mail = email_utils.make_mail(subject=subject,
                                         text_template=text_template,
                                         html_template=html_template,
                                         context_vars=context,
                                         from_email='Mozilla Support Forum '
                                         '<*****@*****.**>',
                                         to_email=user.email)

            return mail

        for u, w in users_and_watches:
            auth_str = get_auth_str(self.answer.question.creator)

            c['answer_url'] = self.answer.get_absolute_url()
            c['helpful_url'] = self.answer.get_helpful_answer_url()
            c['solution_url'] = self.answer.get_solution_url(watch=w[0])

            for k in ['answer_url', 'helpful_url', 'solution_url']:
                c[k] = add_utm(urlparams(c[k], auth=auth_str),
                               'questions-reply')

            c['to_user'] = u
            c['watch'] = w[0]  # TODO: Expose all watches.

            # u here can be a Django User model or a Tidings EmailUser
            # model. In the case of the latter, there is no associated
            # profile, so we set the locale to en-US.
            if hasattr(u, 'profile'):
                locale = u.profile.locale
                tzinfo = u.profile.timezone
            else:
                locale = 'en-US'
                tzinfo = timezone(settings.TIME_ZONE)

            c['created'] = format_datetime(self.answer.created,
                                           tzinfo=tzinfo,
                                           locale=locale.replace('-', '_'))

            yield _make_mail(locale, u, c)
示例#58
0
 def _formatted_datetime(self, dt):
     return format_datetime(localtime(dt),
                            locale=get_current_babel_locale())
示例#59
0
def create_reseller_invoice_for_legal_entity(legal_entity,
                                             start_date,
                                             end_date,
                                             do_send_email=True):
    """
    Args:
        legal_entity (LegalEntity) 
        start_date (long)
        end_date (long)
        do_send_email (bool)
    """
    if legal_entity.is_mobicage:
        # To avoid a composite index we don't filter on is_mobicage
        return
    solution_server_settings = get_solution_server_settings()
    from_email = solution_server_settings.shop_no_reply_email
    to_emails = solution_server_settings.shop_payment_admin_emails
    mobicage_legal_entity = get_mobicage_legal_entity()
    logging.info(
        'Exporting reseller invoices for legal entity %s(id %d) from %s(%s) to %s(%s)',
        legal_entity.name, legal_entity.id, start_date, time.ctime(start_date),
        end_date, time.ctime(end_date))
    invoices = list(Invoice.all().filter(
        'legal_entity_id',
        legal_entity.id).filter('paid_timestamp >', start_date).filter(
            'paid_timestamp <', end_date).filter('paid', True).filter(
                'payment_type IN',
                (Invoice.PAYMENT_MANUAL, Invoice.PAYMENT_MANUAL_AFTER)))
    start_time = time.strftime('%m/%d/%Y', time.gmtime(int(start_date)))
    end_time = time.strftime('%m/%d/%Y', time.gmtime(int(end_date)))
    if not invoices:
        message = 'No new invoices for reseller %s for period %s - %s' % (
            legal_entity.name, start_time, end_time)
        logging.info(message)
        if do_send_email:
            send_mail(from_email, to_emails, message, message)
        return
    items_per_customer = {}
    customers_to_get = set()
    products = {
        p.code: p
        for p in Product.list_by_legal_entity(legal_entity.id)
    }
    for invoice in invoices:
        # get all subscription order items
        order_items = list(OrderItem.list_by_order(invoice.order_key))
        for item in reversed(order_items):
            product = products[item.product_code]
            # We're only interested in subscription items
            if product.is_subscription or product.is_subscription_extension or product.is_subscription_discount:
                if invoice.customer_id not in items_per_customer:
                    items_per_customer[invoice.customer_id] = []
                    customers_to_get.add(
                        Customer.create_key(invoice.customer_id))
                items_per_customer[invoice.customer_id].append(item)
            else:
                order_items.remove(item)
    if not customers_to_get:
        message = 'No new invoices containing subscriptions for reseller %s for period %s - %s' % (
            legal_entity.name, start_time, end_time)
        logging.info(message)
        if do_send_email:
            send_mail(from_email, to_emails, message, message)
        return
    customers = {c.id: c for c in db.get(customers_to_get)}
    product_totals = {}
    for customer_id in items_per_customer:
        items = items_per_customer[customer_id]
        for item in items:
            if item.product_code not in product_totals:
                product_totals[item.product_code] = {
                    'count': 0,
                    'price': int(item.price * legal_entity.revenue_percent)
                }
            product_totals[item.product_code]['count'] += item.count
    total_amount = 0
    for product in product_totals:
        p = product_totals[product]
        price = p['count'] * p['price']
        p['total_price'] = format_currency(
            price / 100.,
            legal_entity.currency_code,
            locale=mobicage_legal_entity.country_code)
        total_amount += price
    total_amount_formatted = format_currency(
        total_amount / 100.,
        legal_entity.currency_code,
        locale=mobicage_legal_entity.country_code)
    vat_amount = total_amount / mobicage_legal_entity.vat_percent if mobicage_legal_entity.country_code == legal_entity.country_code else 0
    vat_amount_formatted = format_currency(
        vat_amount / 100.,
        legal_entity.currency_code,
        locale=mobicage_legal_entity.country_code)
    from_date = format_datetime(datetime.utcfromtimestamp(start_date),
                                locale=SHOP_DEFAULT_LANGUAGE,
                                format='dd/MM/yyyy HH:mm')
    until_date = format_datetime(datetime.utcfromtimestamp(end_date),
                                 locale=SHOP_DEFAULT_LANGUAGE,
                                 format='dd/MM/yyyy HH:mm')

    solution_server_settings = get_solution_server_settings()
    template_variables = {
        'products':
        products,
        'customers':
        customers,
        'invoices':
        invoices,
        'items_per_customer':
        items_per_customer,
        'product_totals':
        product_totals.items(),
        'mobicage_legal_entity':
        mobicage_legal_entity,
        'legal_entity':
        legal_entity,
        'language':
        SHOP_DEFAULT_LANGUAGE,
        'from_date':
        from_date,
        'until_date':
        until_date,
        'revenue_percent':
        legal_entity.revenue_percent,
        'vat_amount_formatted':
        vat_amount_formatted,
        'total_amount_formatted':
        total_amount_formatted,
        'logo_path':
        '../html/img/osa_white_en_250.jpg',
        'tos_link':
        '<a href="%s">%s</a>' %
        (solution_server_settings.shop_privacy_policy_url,
         solution_server_settings.shop_privacy_policy_url)
    }
    source_html = SHOP_JINJA_ENVIRONMENT.get_template(
        'invoice/reseller_invoice.html').render(template_variables)
    output_stream = StringIO()
    pisa.CreatePDF(src=source_html,
                   dest=output_stream,
                   path='%s/invoice' % SHOP_TEMPLATES_FOLDER)
    invoice_pdf_contents = output_stream.getvalue()
    output_stream.close()
    # Create an order, order items, charge and invoice.
    _now = now()
    customer = legal_entity.get_or_create_customer()
    mobicage_team = RegioManagerTeam.get_mobicage()

    def trans():
        to_put = list()
        order_number = OrderNumber.next(mobicage_legal_entity)
        order_key = db.Key.from_path(Order.kind(),
                                     order_number,
                                     parent=customer.key())
        order = Order(key=order_key)
        order.contact_id = legal_entity.contact_id
        order.date = _now
        order.vat_pct = mobicage_legal_entity.vat_percent if legal_entity.country_code == mobicage_legal_entity.country_code else 0
        order.amount = int(round(total_amount))
        order.vat = int(round(vat_amount))
        order.total_amount = int(round(total_amount + vat_amount))
        order.is_subscription_order = False
        order.is_subscription_extension_order = False
        order.team_id = mobicage_team.id
        order.manager = customer.manager
        order.status = Order.STATUS_SIGNED
        to_put.append(order)

        for i, (product_code, item) in enumerate(product_totals.iteritems()):
            order_item = OrderItem(parent=order_key)
            order_item.number = i + 1
            order_item.comment = products[product_code].default_comment(
                SHOP_DEFAULT_LANGUAGE)
            order_item.product_code = product_code
            order_item.count = item['count']
            order_item.price = item['price']
            to_put.append(order_item)

        charge_key = Charge.create_key(allocate_id(Charge), order_number,
                                       customer.id)
        charge = Charge(key=charge_key)
        charge.date = _now
        charge.type = Charge.TYPE_ORDER_DELIVERY
        charge.amount = order.amount
        charge.vat_pct = order.vat_pct
        charge.vat = order.vat
        charge.total_amount = order.total_amount
        charge.manager = order.manager
        charge.team_id = order.team_id
        charge.charge_number = ChargeNumber.next(mobicage_legal_entity)
        charge.currency_code = legal_entity.currency_code
        to_put.append(charge)

        invoice_number = InvoiceNumber.next(mobicage_legal_entity)
        invoice = Invoice(key_name=invoice_number,
                          parent=charge,
                          amount=charge.amount,
                          vat_pct=charge.vat_pct,
                          vat=charge.vat,
                          total_amount=charge.total_amount,
                          currency_code=legal_entity.currency_code,
                          date=_now,
                          payment_type=Invoice.PAYMENT_MANUAL_AFTER,
                          operator=charge.manager,
                          paid=False,
                          legal_entity_id=mobicage_legal_entity.id,
                          pdf=invoice_pdf_contents)
        charge.invoice_number = invoice_number
        to_put.append(invoice)
        put_and_invalidate_cache(*to_put)
        return order, charge, invoice

    order, charge, invoice = run_in_xg_transaction(trans)

    if do_send_email:
        serving_url = '%s/internal/shop/invoice/pdf?customer_id=%d&order_number=%s&charge_id=%d&invoice_number=%s' % (
            get_server_settings().baseUrl, customer.id, order.order_number,
            charge.id, invoice.invoice_number)
        subject = 'New reseller invoice for %s, %s - %s' % (
            legal_entity.name, start_time, end_time)
        body_text = 'A new invoice is available for reseller %s for period %s to %s here: %s' % (
            legal_entity.name, start_time, end_time, serving_url)

        send_mail(from_email, to_emails, subject, body_text)
示例#60
0
文件: checkers.py 项目: ateska/striga
    def test_2_num_plurals_checkers(self):
        # in this testcase we add an extra msgstr[idx], we should be
        # disregarding it
        for _locale in [p for p in PLURALS if PLURALS[p][0] == 2]:
            if _locale in ['nn', 'no']:
                _locale = 'nn_NO'
                num_plurals = PLURALS[_locale.split('_')[0]][0]
                plural_expr = PLURALS[_locale.split('_')[0]][1]
            else:
                num_plurals = PLURALS[_locale][0]
                plural_expr = PLURALS[_locale][1]
            try:
                locale = Locale(_locale)
                date = format_datetime(datetime.now(LOCALTZ),
                                       'yyyy-MM-dd HH:mmZ',
                                       tzinfo=LOCALTZ,
                                       locale=_locale),
            except UnknownLocaleError:
                # Just an alias? Not what we're testing here, let's continue
                continue
            po_file = (ur"""\
# %(english_name)s translations for TestProject.
# Copyright (C) 2007 FooBar, Inc.
# This file is distributed under the same license as the TestProject
# project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2007.
#
msgid ""
msgstr ""
"Project-Id-Version: TestProject 0.1\n"
"Report-Msgid-Bugs-To: [email protected]\n"
"POT-Creation-Date: 2007-04-01 15:30+0200\n"
"PO-Revision-Date: %(date)s\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: %(locale)s <*****@*****.**>\n"
"Plural-Forms: nplurals=%(num_plurals)s; plural=%(plural_expr)s\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel %(version)s\n"

#. This will be a translator comment,
#. that will include several lines
#: project/file1.py:8
msgid "bar"
msgstr ""

#: project/file2.py:9
msgid "foobar"
msgid_plural "foobars"
msgstr[0] ""
msgstr[1] ""
msgstr[2] ""

""" % dict(locale=_locale,
            english_name=locale.english_name,
            version=VERSION,
            year=time.strftime('%Y'),
            date=date,
            num_plurals=num_plurals,
            plural_expr=plural_expr)).encode('utf-8')
            # we should be adding the missing msgstr[0]

            # This test will fail for revisions <= 406 because so far
            # catalog.num_plurals was neglected
            catalog = read_po(StringIO(po_file), _locale)
            message = catalog['foobar']
            checkers.num_plurals(catalog, message)