Пример #1
0
def convert(in_c, out_c, count, ctx):
    rate = get_rate(in_c, out_c)
    out = {}
    result = round(number_conv(count) * float(list(rate.values())[0]), 2)
    out['in'] = "<b>{}</b> <i>{}</i>".format(
        format_decimal(number_conv(count), locale=ctx.locale),
        get_currency_name(in_c.upper(),
                          locale=ctx.locale,
                          count=number_conv(count)))
    out['out'] = "<b>{}</b> <i>{}</i>".format(
        format_decimal(result, locale=ctx.locale),
        get_currency_name(out_c.upper(),
                          locale=ctx.locale,
                          count=number_conv(count)))
    return out
Пример #2
0
def get_currencies():
    properties = get_tenant_properties()

    currencies = set(
        itertools.chain(*[
            list(method['currencies'].keys())
            for method in properties.PAYMENT_METHODS
        ]))
    min_amounts = get_min_amounts(properties.PAYMENT_METHODS)

    currencies = [{
        'code': code,
        'name': get_currency_name(code),
        'symbol': get_currency_symbol(code).replace('US$', '$')
    } for code in currencies]

    for currency in currencies:
        if currency['code'] in min_amounts:
            currency['minAmount'] = min_amounts[currency['code']]
        try:
            currency['rate'] = get_rate(properties.DEFAULT_CURRENCY,
                                        currency['code'])
        except (MissingRate, ProgrammingError):
            currency['rate'] = 1

    return currencies
Пример #3
0
def get_currency_settings():
    result = []
    for provider in PaymentProvider.objects.all():
        for cur in provider.paymentcurrency_set.all():
            result.append({
                'provider':
                provider.name,
                'code':
                cur.code,
                'name':
                get_currency_name(cur.code),
                'symbol':
                get_currency_symbol(cur.code).replace('US$', '$'),
                'defaultAmounts': [
                    cur.default1,
                    cur.default2,
                    cur.default3,
                    cur.default4,
                ],
                'minAmount':
                cur.min_amount,
                'maxAmount':
                cur.max_amount
            })
    return result
Пример #4
0
    def get_name(self, locale: str, count: Optional[int] = None) -> str:
        from babel.numbers import get_currency_name

        return get_currency_name(  # type: ignore[no-any-return]
            self.code,
            locale=locale,
            count=count,
        )
Пример #5
0
 def get_currency_choices(cls):
     currencies = []
     if isinstance(connection.tenant, FakeTenant):
         currencies = [('EUR', 'Euro')]
     else:
         for provider in cls.objects.all():
             for cur in provider.paymentcurrency_set.all():
                 currency = (cur.code, get_currency_name(cur.code))
                 if currency not in currencies:
                     currencies.append(currency)
     return currencies
Пример #6
0
    def get_currency_name(self, currency, count=None):
        """Return the name used for the specified currency

        In:
          - ``currency`` -- the currency code
          - ``count`` -- If provided the currency name will be pluealized to that number

        Return:
          - the currency name
        """
        return numbers.get_currency_name(currency, count, self)
Пример #7
0
def create_token_agreement_pdf(full_name, address, amount, currency_full, currency_short, token, payment_info,
                               has_verified_utility_bill):
    # don't forget to update intercom tags when adding new contracts / tokens
    def fmt(x, currency):
        if currency == 'BTC':
            return '{:.8f}'.format(x)
        return '{:.2f}'.format(x)

    amount_formatted = fmt(amount, currency_short)
    stats = get_global_stats(token)
    conversion = {currency.currency: fmt(round_currency_amount(currency.currency, currency.value / stats.value),
                                         currency.currency)
                  for currency in stats.currencies}

    template_variables = {
        'logo_path': 'assets/logo.jpg',
        'effective_date': _get_effective_date(),
        'full_name': full_name,
        'address': address.replace('\n', ', '),
        'amount': amount_formatted,
        'currency_full': currency_full,
        'price': stats.value,
        'price_words': inflect.engine().number_to_words(stats.value).title(),
        'currency_short': currency_short,
        'conversion': conversion
    }

    if token == TOKEN_ITFT:
        html_file = 'token_itft.html'
        context = {'bank_account': get_bank_account_info(currency_short, payment_info or [], has_verified_utility_bill)}
        context.update(template_variables)
        md = JINJA_ENVIRONMENT.get_template('token_itft.md').render(context)
        markdown_to_html = markdown.markdown(md, extensions=['markdown.extensions.tables'])
        template_variables['markdown_to_html'] = markdown_to_html.replace('<th', '<td')
        template_variables['title'] = u'iTFT Purchase Agreement'
    else:
        currency_messages = []
        for currency in BANK_ACCOUNTS:
            account = BANK_ACCOUNTS[currency]
            if currency == 'BTC':
                currency_messages.append(
                    u'when using Bitcoin: to the Company’s BitCoin wallet hosted by BitOasis Technologies FZE, at the'
                    u' following digital address: <b>%s</b> (the “<b>Wallet</b>”)' % account)
            else:
                currency_messages.append(
                    u'when using %s: to the Company’s bank account at Mashreq Bank, IBAN: <b>%s</b> SWIFT/BIC:'
                    u' <b>BOMLAEAD</b>' % (get_currency_name(currency, locale='en_GB'), account))

        template_variables['currency_messages'] = currency_messages
        html_file = 'token_tft_btc.html' if currency_short == 'BTC' else 'token_tft.html'

    return _render_pdf_from_html(html_file, template_variables)
Пример #8
0
    def get_currency_name(self, currency):
        """Return the name used for the specified currency

        >>> Locale('en', 'US').get_currency_name('USD')
        u'US Dollar'

        In:
          - ``currency`` -- the currency code

        Return:
          - the currency name
        """
        return numbers.get_currency_name(currency, self)
Пример #9
0
    def get_currency_name(self, currency, count=None):
        """Return the name used for the specified currency

        >>> Locale('en', 'US').get_currency_name('USD')
        u'US Dollar'

        In:
          - ``currency`` -- the currency code
          - ``count`` -- If provided the currency name will be pluealized to that number

        Return:
          - the currency name
        """
        return numbers.get_currency_name(currency, count, self)
Пример #10
0
    def name(cls) -> str:
        """Automatic currency name.

        Example::

            from babel.numbers import get_currency_name
            In: get_currency_name('AMD')
            Out: 'Armenian Dram'

            In: get_currency_name('AMD', locale='hy_AM')
            Out: 'հայկական դրամ'

            In: get_currency_name('AMD', locale='nl_NL')
            Out: 'Armeense dram'

        :return:
        """
        return get_currency_name(cls.uid)
Пример #11
0
    def _format_currency_long_name(self, locale):
        # This reproduces some of bable.numbers._format_currency_long_name
        # Step 3.
        unit_pattern = get_currency_unit_pattern(self.options.currency,
                                                 count=self,
                                                 locale=locale)

        # Step 4.
        display_name = get_currency_name(self.options.currency,
                                         count=self,
                                         locale=locale)

        # Step 5.
        base_pattern = locale.decimal_formats.get(None)
        pattern = self._apply_options(base_pattern)

        number_part = pattern.apply(
            self,
            locale,
            currency=self.options.currency,
        )
        return unit_pattern.format(number_part, display_name)
Пример #12
0
def get_currencies():
    properties = get_tenant_properties()

    currencies = set(itertools.chain(*[
        method['currencies'].keys() for method in properties.PAYMENT_METHODS
    ]))
    min_amounts = get_min_amounts(properties.PAYMENT_METHODS)

    currencies = [{
        'code': code,
        'name': get_currency_name(code),
        'symbol': get_currency_symbol(code)
    } for code in currencies]

    for currency in currencies:
        if currency['code'] in min_amounts:
            currency['minAmount'] = min_amounts[currency['code']]

        try:
            currency['rate'] = get_rate(currency['code'])
        except (CurrencyConversionException, ProgrammingError):
            currency['rate'] = 1

    return currencies
Пример #13
0
    ("XAF", "Communauté Financière Africaine (BEAC) CFA Franc BEAC"),
    ("XCD", "East Caribbean Dollar"),
    ("XDR", "International Monetary Fund (IMF) Special Drawing Rights"),
    ("XOF", "Communauté Financière Africaine (BCEAO) Franc"),
    ("XPF", "Comptoirs Français du Pacifique (CFP) Franc"),
    ("YER", "Yemen Rial"),
    ("ZAR", "South Africa Rand"),
    ("ZMW", "Zambia Kwacha"),
    ("ZWD", "Zimbabwe Dollar"),
]

CURRENCY_SYMBOLS = [
    get_currency_symbol(c[0], locale="en.US") for c in CURRENCY_CODES
]
CURRENCY_NAMES = [
    get_currency_name(c[0], locale="en.US") for c in CURRENCY_CODES
]


def get_currency_tokens(use_currency_name=True):
    currency_symbols = [
        t for t in CURRENCY_SYMBOLS if not re.search("[A-Za-z]", t)
    ]  # '$, ₣, ...'

    # Pick up only the units of currency. (dollar, franc, ...)
    currency_names = []
    if use_currency_name:
        # List up major currency names for now to make it less noisy.
        currency_names = ['Dollar', 'Yen']
        currency_names = [x.lower() for x in currency_names]
        #currency_names = [n.split()[-1].lower() for n in CURRENCY_NAMES if not re.search("[0-9\(\)]", n)]
Пример #14
0
def _get_currency_name(currency):
    if currency in SUPPORTED_CRYPTO_CURRENCIES:
        return CRYPTO_CURRENCY_NAMES[currency]
    return get_currency_name(currency, locale='en_GB')
Пример #15
0
def test_get_currency_name():
    assert numbers.get_currency_name('USD', 'en_US') == 'US dollars'
Пример #16
0
# THE SOFTWARE.
"""
Tool to generate the tables we need at runtime.
It uses the real babel package
"""
from babel import numbers  # For currency presentation.
from kicost.currency_converter.default_rates import default_rates

print('#!/usr/bin/python3')
print('# -*- coding: utf-8 -*-')
first = True
for currency in sorted(default_rates.keys()):
    if first:
        indent = 'currency_symbols = {'
        first = False
    else:
        indent = '                    '
    print(indent + "'{}': '{}',".format(
        currency, numbers.get_currency_symbol(currency, locale='en_US')))
print('                    }')
first = True
for currency in sorted(default_rates.keys()):
    if first:
        indent = 'currency_names = {'
        first = False
    else:
        indent = '                  '
    print(indent + "'{}': '{}',".format(
        currency, numbers.get_currency_name(currency, locale='en_US')))
print('                  }')
Пример #17
0
 def get_name(self, locale, count=None):
     from babel.numbers import get_currency_name
     return get_currency_name(self.code, locale=locale, count=count)
Пример #18
0
def get_currency_choices():
    currencies = []
    for method in properties.PAYMENT_METHODS:
        currencies += method['currencies'].keys()

    return [(currency, get_currency_name(currency, locale='en')) for currency in set(currencies)]
Пример #19
0
def test_get_currency_name():
    assert numbers.get_currency_name('USD', locale='en_US') == u'US Dollar'
    assert numbers.get_currency_name('USD', count=2, locale='en_US') == u'US dollars'
Пример #20
0
    def display_name(self, locale='en_US'):
        """Returns the name used by the locale for this currency."""

        return get_currency_name(self._code, locale=locale)
Пример #21
0
def test_get_currency_name():
    assert numbers.get_currency_name('USD', 'en_US') == u'US dollars'
Пример #22
0
def test_get_currency_name():
    assert numbers.get_currency_name('USD', locale='en_US') == u'US Dollar'
    assert numbers.get_currency_name('USD', count=2,
                                     locale='en_US') == u'US dollars'
Пример #23
0
def create_token_agreement_pdf(full_name,
                               address,
                               amount,
                               currency_full,
                               currency_short,
                               token=TOKEN_TFT):
    # don't forget to update intercom tags when adding new contracts / tokens

    if token == TOKEN_ITFT:
        html_file = 'token_itft.html'
    elif currency_short == 'BTC':
        html_file = 'token_tft_btc.html'
    else:
        html_file = 'token_tft.html'

    if currency_short == 'BTC':
        amount_formatted = '{:.8f}'.format(amount)
    else:
        amount_formatted = '{:.2f}'.format(amount)
    conversion = {}
    if token:
        stats = get_global_stats(TOKEN_TFT)
        conversion = {
            currency.currency:
            round_currency_amount(currency.currency,
                                  currency.value / stats.value)
            for currency in stats.currencies
        }
    currency_messages = []
    for currency in BANK_ACCOUNTS:
        account = BANK_ACCOUNTS[currency]
        if currency == 'BTC':
            currency_messages.append(
                u'when using Bitcoin: to the Company’s BitCoin wallet hosted by BitOasis Technologies FZE, at the'
                u' following digital address: <b>%s</b> (the “<b>Wallet</b>”)'
                % account)
        else:
            currency_messages.append(
                u'when using %s: to the Company’s bank account at Mashreq Bank, IBAN: <b>%s</b> SWIFT/BIC:'
                u' <b>BOMLAEAD</b>' %
                (get_currency_name(currency, locale='en_GB'), account))
    template_variables = {
        'logo_path': 'assets/logo.jpg',
        'effective_date': _get_effective_date(),
        'full_name': full_name,
        'address': address,
        'amount': amount_formatted,
        'currency_full': currency_full,
        'currency_short': currency_short,
        'currency_messages': currency_messages,
        'conversion': conversion
    }

    source_html = JINJA_ENVIRONMENT.get_template(html_file).render(
        template_variables)

    output_stream = StringIO()
    pisa.CreatePDF(src=source_html,
                   dest=output_stream,
                   path='%s' % ASSETS_FOLDER)
    pdf_contents = output_stream.getvalue()
    output_stream.close()

    return pdf_contents