def currency_format(context, value, currency='EUR', decimal=2):
    if value is None:
        value = 0.0

    lang = translation.get_language()
    locale = context.get('locale', lang)

    if isinstance(value, six.string_types):
        symbol = get_currency_symbol(currency, locale=locale)
        if not symbol:
            symbol = currency
        return mark_safe('%s %s' % (value, symbol))

    value = round(value, decimal)
    formatted = format_currency(value, currency, locale=locale)
    symbol = get_currency_symbol(currency, locale=locale)
    if not context.get('filter_country') and len(symbol) == 1:
        # When we have possibly mixed currencies, show three letter symbol
        # This improves alignment
        formatted = formatted.replace(symbol, currency)
    if decimal == 0:
        zero_amount = format_currency(0, currency, locale=locale)
        zero_decimals = zero_amount.replace(symbol, '').strip()[1:]
        formatted = formatted.replace(zero_decimals, '')
    return mark_safe(formatted.replace(' ', ' '))
def currency_format(context, value, currency='EUR', decimal=2):
    if value is None:
        value = 0.0

    lang = translation.get_language()
    locale = context.get('locale', lang)

    if isinstance(value, six.string_types):
        symbol = get_currency_symbol(currency, locale=locale)
        if not symbol:
            symbol = currency
        return mark_safe('%s %s' % (value, symbol))

    value = round(value, decimal)
    formatted = format_currency(value, currency, locale=locale)
    symbol = get_currency_symbol(currency, locale=locale)
    if not context.get('filter_country') and len(symbol) == 1:
        # When we have possibly mixed currencies, show three letter symbol
        # This improves alignment
        formatted = formatted.replace(symbol, currency)
    if decimal == 0:
        zero_amount = format_currency(0, currency, locale=locale)
        zero_decimals = zero_amount.replace(symbol, '').strip()[1:]
        formatted = formatted.replace(zero_decimals, '')
    return mark_safe(formatted.replace(' ', ' '))
Beispiel #3
0
 def set_limit_up(self, update, context):
     user_id = update.message.chat_id
     if not user_id in users.keys():
         try:
             users[user_id] = UserData(context.job.context[0])
         except:
             msg = "Fehler. Schon /set geschickt?"
     else:
         if len(update.message.text.split()) == 2:
             limit = update.message.text.split()[1]
             if get_currency_symbol(CURRENCY) in limit:
                 if users[user_id].amount:
                     up_limit = int(
                         limit.replace(get_currency_symbol(CURRENCY),
                                       "")) / users[user_id].amount
                 print("Umgerechnet: ", up_limit)
             else:
                 up_limit = int(limit)
             users[user_id].up = up_limit
             if users[user_id].up == 0:
                 msg = "Up-Limit gelöscht."
             else:
                 msg = f"Neues Up-Limit: {format_currency(users[user_id].up, CURRENCY.upper(), locale='de_DE')}"
         else:
             msg = f"Aktuelles Up-Limit: {format_currency(users[user_id].up, CURRENCY.upper(), locale='de_DE')}"
     logging.info(f"Price limit up for {user_id}: {msg}")
     update.message.reply_text(msg)
def parse_value(value):
    """
    Accepts a string value and attempts to parce it as a currency value.

    Returns the extracted numeric value converted to a string
    """
    l_currency_language_code, l_currency_code = _getCodes()

    curSym = get_currency_symbol(l_currency_code, l_currency_language_code)
    grpSym = get_group_symbol(locale=l_currency_language_code.lower())
    decSym = get_decimal_symbol(locale=l_currency_language_code.lower())

    # Convert the Official characters into what comes from the keyboard.
    #   This section may need to grow over time.
    #   - Character 160 is a non-breaking space, which is different from a typed space
    if ord(grpSym) == 160:
        value = value.replace(u' ', grpSym)

    allSym = _getSymbols(value)
    invalidSym = allSym.replace(curSym, '').replace(
        grpSym, '').replace(decSym, '').replace(u'-', '')

    value = value.replace(curSym, '')

    if allSym.count(decSym) > 1:
        raise NumberFormatError(default_error_messages['decimal_symbol'] % decSym)
    if (allSym.count(decSym) == 1 and allSym[-1] != decSym) or invalidSym:
        raise NumberFormatError(default_error_messages['invalid_format'] % (grpSym, decSym))
    if value.count(decSym) == 1:
        value = parse_decimal(value, locale=l_currency_language_code.lower())
    else:
        value = parse_number(value, locale=l_currency_language_code.lower())

    # The value is converted into a string because the parse functions return floats
    return str(value)
Beispiel #5
0
def format_currency(number, currency, locale = 'en'):
    if number is None: number = 0
    if round(number) == number:
        return u'{}{}'.format(get_currency_symbol(currency, locale = locale), format_int_amount(number, locale))
    else:
        fnumber = Decimal('%.2f' % number)
        return fc(fnumber, currency, locale = locale)
Beispiel #6
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
def parse_value(value):
    """
    Accepts a string value and attempts to parce it as a currency value.

    Returns the extracted numeric value converted to a string
    """
    l_currency_language_code, l_currency_code = _getCodes()

    curSym = get_currency_symbol(l_currency_code, l_currency_language_code)
    grpSym = get_group_symbol(locale=l_currency_language_code.lower())
    decSym = get_decimal_symbol(locale=l_currency_language_code.lower())

    # Convert the Official characters into what comes from the keyboard.
    #   This section may need to grow over time.
    #   - Character 160 is a non-breaking space, which is different from a typed space
    if ord(grpSym) == 160:
        value = value.replace(u" ", grpSym)

    allSym = _getSymbols(value)
    invalidSym = allSym.replace(curSym, "").replace(grpSym, "").replace(decSym, "").replace(u"-", "")

    value = value.replace(curSym, "")

    if allSym.count(decSym) > 1:
        raise NumberFormatError(default_error_messages["decimal_symbol"] % decSym)
    elif (allSym.count(decSym) == 1 and allSym[-1] != decSym) or len(invalidSym) > 0:
        raise NumberFormatError(default_error_messages["invalid_format"] % (grpSym, decSym))
    elif value.count(decSym) == 1:
        value = parse_decimal(value, locale=l_currency_language_code.lower())
    else:
        value = parse_number(value, locale=l_currency_language_code.lower())

    # The value is converted into a string because the parse functions return
    # floats
    return str(value)
Beispiel #8
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
Beispiel #9
0
def currency(context, value):
    #return '${:20,.2f}'.format(float(value))
    if value is not None:
        request = context.get('request', False)
        return numbers.format_currency(
            float(value),
            numbers.get_currency_symbol('USD', 'en_US'),
            u'\xa4\xa4 #,##0.00', locale=request.LANGUAGE_CODE.replace('-', '_')
        )
    return ''
def add_currency_symbol():
    """
    Context processor to inject the proper currency symbol into the Jinja2
    context as the "CURRENCY_SYM" variable.

    :return: proper currency symbol for our locale and currency
    :rtype: str
    """
    return dict(CURRENCY_SYM=get_currency_symbol(
        settingsmod.CURRENCY_CODE, locale=settingsmod.LOCALE_NAME))
Beispiel #11
0
    def get_currency_symbol(self, currency):
        """Return the symbol used for the specified currency

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

        Return:
          - the currency symbol
        """
        return numbers.get_currency_symbol(currency, self)
Beispiel #12
0
def render_localized_currency(code, detailed=True):
    if code == "XXX":
        return _("No Currency")
    locale = get_locale() or "en_US"
    symbol = get_currency_symbol(code, locale=locale)
    details = ""
    if detailed:
        details = f" − {get_currency_name(code, locale=locale)}"
    if symbol == code:
        return f"{code}{details}"
    else:
        return f"{code} − {symbol}{details}"
Beispiel #13
0
 def verified_mode(self):
     """
     Return verified mode information, or None.
     """
     mode = CourseMode.verified_mode_for_course(self.course_key)
     if mode:
         return {
             'price': mode.min_price,
             'currency': mode.currency.upper(),
             'currency_symbol': get_currency_symbol(mode.currency.upper()),
             'sku': mode.sku,
             'upgrade_url': verified_upgrade_deadline_link(self.effective_user, self.overview),
         }
Beispiel #14
0
    def get_currency_symbol(self, currency):
        """Return the symbol used for the specified currency

        >>> Locale('en', 'US').get_currency_symbol('USD')
        u'$'

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

        Return:
          - the currency symbol
        """
        return numbers.get_currency_symbol(currency, self)
Beispiel #15
0
    def convert(self, text):
        """Convert currency according to the target locale

           Args:
              text (str): currency text
           Returns:
              (str): converted currency
        """

        cur = parse_price(re.sub('\s', ' ', text))

        if cur.amount and cur.currency:
            amountText, currency = cur.amount_text, cur.currency
            if self.srcDecimalSymbol in amountText:
                amount = float(cur.amount)
                res = format_currency(amount,
                                      self.curCode,
                                      locale=self.tgtLocale)
            else:
                amount = int(cur.amount)
                if self.tgtLang == 'eng':
                    res = format_currency(amount,
                                          self.curCode,
                                          format=u'¤#,##0',
                                          locale=self.tgtLocale,
                                          currency_digits=False)
                elif self.tgtLang == 'fra':
                    res = format_currency(amount,
                                          self.curCode,
                                          format=u'#,##0\xa0¤',
                                          locale=self.tgtLocale,
                                          currency_digits=False)
                else:
                    raise NotImplementedError(
                        'Target language %s is not supported' %
                        (self.tgtLang, ))

            if self._curFormat == 'symbol':
                tgtCurrencySymbol = numbers.get_currency_symbol(
                    self.curCode, self.srcLocale)
                res = re.sub(
                    re.escape(tgtCurrencySymbol) + r'\S+', tgtCurrencySymbol,
                    res)
        else:
            res = None

        return res
Beispiel #16
0
def serialize_upgrade_info(user, course_overview, enrollment):
    """
    Return verified mode upgrade information, or None.

    This is used in a few API views to provide consistent upgrade info to frontends.
    """
    if not can_show_verified_upgrade(user, enrollment):
        return None

    mode = CourseMode.verified_mode_for_course(course=course_overview)
    return {
        'access_expiration_date': get_user_course_expiration_date(user, course_overview),
        'currency': mode.currency.upper(),
        'currency_symbol': get_currency_symbol(mode.currency.upper()),
        'price': mode.min_price,
        'sku': mode.sku,
        'upgrade_url': verified_upgrade_deadline_link(user, course_overview),
    }
Beispiel #17
0
 def render(self, name, value, attrs=None):
     u"""Render base widget and add bootstrap spans"""
     field = super(BootstrapCurrencyDecimalWidget, self).render(name, value, attrs)
     settingObj = None
     if self.user:
         settingObj = self.user.get_profile().currency
     currency = 'USD'
     if settingObj:
         currency = settingObj
     locale = get_current_locale()
     if not locale:
         Locale = babel.core.Locale
         locale = Locale.parse(to_locale(get_language()))
     return mark_safe((
         u'<div class="input-group">'
         u'    <span class="input-group-addon">%(data)s</span>%(field)s'
         u'</div>'
     ) % {'field': field, 'data': get_currency_symbol(currency, locale)})
Beispiel #18
0
    def symbol(cls) -> str:
        """Automatic currency symbol.

        Example::

            from babel.numbers import get_currency_symbol
            In: get_currency_symbol('AMD')
            Out: 'AMD'

            In: get_currency_symbol('AMD', locale='hy_AM')
            Out: '֏'

            In: get_currency_symbol('AMD', locale='nl_NL')
            Out: 'AMD'

        :return:
        """
        return get_currency_symbol(cls.uid)
Beispiel #19
0
def accounts_list():
    """Returns a string with account information in ledger format"""
    temp = ""
    accounts = data.accounts.values()
    for acc in accounts:
        #Ignore "dummy" accounts
        if acc.type is None or acc.type == "ROOT":
            continue
        #Ignore template transactions 
        if str(acc.commodity) == "template":
            continue
        temp += "account {}\n".format(full_acc_name(acc))
        if acc.description:
            temp+="\tnote {}\n".format(acc.description)
        temp += "\tcheck commodity == \"{}\"\n".format(get_currency_symbol(
            str(acc.commodity)))
        temp += "\n"
    return temp
Beispiel #20
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
Beispiel #21
0
    def verified_mode(self):
        """
        Return verified mode information, or None.
        """
        if not can_show_verified_upgrade(self.effective_user,
                                         self.enrollment_object):
            return None

        mode = CourseMode.verified_mode_for_course(self.course_key)
        return {
            'access_expiration_date':
            get_user_course_expiration_date(self.effective_user,
                                            self.overview),
            'price':
            mode.min_price,
            'currency':
            mode.currency.upper(),
            'currency_symbol':
            get_currency_symbol(mode.currency.upper()),
            'sku':
            mode.sku,
            'upgrade_url':
            verified_upgrade_deadline_link(self.effective_user, self.overview),
        }
Beispiel #22
0
 def lookups(self, request, model_admin):
     return [(cur, get_currency_symbol(cur))
             for cur in Funding.objects.values_list('target_currency',
                                                    flat=True).distinct()]
Beispiel #23
0
def test_get_currency_symbol():
    assert numbers.get_currency_symbol('USD', 'en_US') == u'$'
Beispiel #24
0
def format_currency(value):
    return numbers.format_currency(
        float(value), numbers.get_currency_symbol("USD", "en_US"), u"\xa4\xa4 #,##0.00", locale="pt_BR"
    )
Beispiel #25
0
    def index(self, **kwargs):
        departure_airport = kwargs.get('departure_airport', None)
        arrival_airport = kwargs.get('arrival_airport', None)
        departure_date = kwargs.get('departure_date', datetime.now())
        arrival_date = kwargs.get('arrival_date', datetime.now())
        markup = self.get_content(departure_airport, arrival_airport,
                                  departure_date, arrival_date)

        document = BeautifulSoup(markup, 'html5lib')
        products = document.find_all('form', class_='product')
        currency_symbol = get_currency_symbol(self.currency,
                                              locale=self.locale)
        trip_repo = TripRepository()
        trips = []
        for product in products:
            price_elem = product.find(class_='product-price')
            price_text = price_elem.find(class_='number').find('span').text
            price = parse_decimal(price_text.replace(currency_symbol, ''),
                                  locale=self.locale)

            legs = product.find_all(class_='leghighlight')
            if len(legs) != 2:
                raise Exception('Cannot parse the provided HTML')

            info_bars = product.find_all(class_='flight-info-bar')
            if len(info_bars) != 2:
                raise Exception('Cannot parse the provided HTML')

            # get the text for the depature time
            out_info_bar = info_bars[0]
            out_date_elem = out_info_bar.find(class_='date')
            outbound_elem = legs[0].find(class_='departure-arrival')
            out_time_elem = outbound_elem.find(class_='time')
            out_datetime_text = ' '.join(out_date_elem.text.split() + out_time_elem.text.split())

            # get the text for the return time
            in_info_bar = info_bars[1]
            in_date_elem = in_info_bar.find(class_='date')
            inbound_elem = legs[1].find(class_='departure-arrival')
            in_time_elem = inbound_elem.find(class_='time')
            in_datetime_text = ' '.join(in_date_elem.text.split() + in_time_elem.text.split())

            # get the datimetime objects for depature and return
            date_format = "%a %d %b %Y %H:%M"
            out_time = datetime.strptime(out_datetime_text, date_format)
            in_time = datetime.strptime(in_datetime_text, date_format)

            # create a new Trip object
            trip = Trip(departure_airport=departure_airport,
                        arrival_airport=arrival_airport,
                        outgoing_date=out_time,
                        incoming_date=in_time)
            trip.price = Price(price,
                               CurrencyRepository().get_by_code(self.currency))
            trip.comment = price_elem.find(class_='taxes').text

            # persist the Trip object
            trip_repo.create(trip)

            # add the trip to the list
            trips.append(trip)

        return trips
Beispiel #26
0
def get_localized_currency_symbol(context, currency_code):
    locale = to_known_locale(context['request'].LANGUAGE_CODE)
    return get_currency_symbol(currency_code.upper(), locale)
Beispiel #27
0
 def currency_symbol(self):
     return get_currency_symbol(self.currency, 'en')
Beispiel #28
0
 def getCurrencySymbol(self, request):
     return get_currency_symbol(self.getCurrency(request), locale='en_US')
Beispiel #29
0
    def symbol(self, locale='en_US'):
        """Returns the symbol used by the locale for this currency."""

        return get_currency_symbol(self._code, locale=locale)
Beispiel #30
0
def _get_symbol(currency_code: str) -> str:
    _, locale_code = get_locale_data()
    return get_currency_symbol(currency_code, locale_code)
Beispiel #31
0
 def getCurrencySymbol(self, request):
     return get_currency_symbol(self.getCurrency(request), locale='en_US')
 def currency_symbol(self):
     return get_currency_symbol(self.currency, 'en')
Beispiel #33
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('                  }')
Beispiel #34
0
    ("VND", "Viet Nam Dong"),
    ("VUV", "Vanuatu Vatu"),
    ("WST", "Samoa Tala"),
    ("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.
Beispiel #35
0
 def currency(self,bizplace_id,user_id):
     symbol=get_currency_symbol(bizplace_store.get(bizplace_id,fields=['currency']))
     user_locale = dbaccess.stores.memberpref_store.get_by(dict(member=user_id), ['language'])[0]['language']
     decimal=get_decimal_symbol(user_locale)
     group=get_group_symbol(user_locale)
     return dict(symbol=symbol, decimal=decimal, group=group)
def get_currency_symbol(currency="GBP"):
    return numbers.get_currency_symbol(currency,
                                       locale=flask_babel.get_locale())
Beispiel #37
0
    def get(self, request, course_id, error=None):  # lint-amnesty, pylint: disable=too-many-statements
        """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_client_ip(request)[0],
            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 'no-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")
            redirect_url = IDVerificationService.get_verify_location(
                course_id=course_key)
            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 self._redirect_to_course_or_dashboard(
                course, course_key, request.user)

        # 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]):
            return self._redirect_to_course_or_dashboard(
                course, course_key, request.user)

        donation_for_course = request.session.get("donation_for_course", {})
        chosen_price = donation_for_course.get(str(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('{}?{}'.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 = str(course_key)
        gated_content = ContentTypeGatingConfig.enabled_for_enrollment(
            user=request.user, course_key=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":
            gated_content,
            "course_duration_limit_enabled":
            CourseDurationLimitConfig.enabled_for_enrollment(
                request.user, course),
        }
        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
            course_price = price_before_discount
            enterprise_customer = enterprise_customer_for_request(request)
            LOG.info(
                '[e-commerce calculate API] Going to hit the API for user [%s] linked to [%s] enterprise',
                request.user.username,
                enterprise_customer.get('name') if isinstance(
                    enterprise_customer, dict) else None  # Test Purpose
            )
            if enterprise_customer and verified_mode.sku:
                course_price = get_course_final_price(request.user,
                                                      verified_mode.sku,
                                                      price_before_discount)

            context["currency"] = verified_mode.currency.upper()
            context["currency_symbol"] = get_currency_symbol(
                verified_mode.currency.upper())
            context["min_price"] = course_price
            context["verified_name"] = verified_mode.name
            context["verified_description"] = verified_mode.description
            # if course_price is equal to price_before_discount then user doesn't entitle to any discount.
            if course_price != price_before_discount:
                context["price_before_discount"] = price_before_discount

            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

        language = get_language()
        context['track_links'] = get_verified_track_links(language)

        duration = get_user_course_duration(request.user, course)
        deadline = duration and get_user_course_expiration_date(
            request.user, course)
        if deadline:
            formatted_audit_access_date = strftime_localized_html(
                deadline, 'SHORT_DATE')
            context['audit_access_deadline'] = formatted_audit_access_date
        fbe_is_on = deadline and gated_content

        # Route to correct Track Selection page.
        # REV-2133 TODO Value Prop: remove waffle flag after testing is completed
        # and happy path version is ready to be rolled out to all users.
        if VALUE_PROP_TRACK_SELECTION_FLAG.is_enabled():
            if not error:  # TODO: Remove by executing REV-2355
                if not enterprise_customer_for_request(
                        request):  # TODO: Remove by executing REV-2342
                    if fbe_is_on:
                        return render_to_response("course_modes/fbe.html",
                                                  context)
                    else:
                        return render_to_response("course_modes/unfbe.html",
                                                  context)

        # If error or enterprise_customer, failover to old choose.html page
        return render_to_response("course_modes/choose.html", context)
Beispiel #38
0
def kicost(in_file,
           eda_name,
           out_filename,
           user_fields,
           ignore_fields,
           group_fields,
           translate_fields,
           variant,
           dist_list=list(distributor_dict.keys()),
           collapse_refs=True,
           suppress_cat_url=True,
           currency=DEFAULT_CURRENCY,
           export_json=False):
    ''' @brief Run KiCost.
    
    Take a schematic input file and create an output file with a cost spreadsheet in xlsx format.
    
    @param in_file `list(str())` List of the names of the input BOM files.
    @param eda_name `list(str())` of the EDA modules to be used to open the `in_file`list.
    @param out_filename `str()` XLSX output file name.
    @param user_fields `list()` of the user fields to be included on the spreadsheet global part.
    @param ignore_fields `list()` of the fields to be ignored on the read EDA modules.
    @param group_fields `list()` of the fields to be grouped/merged on the function group parts that
    are not grouped by default.
    @param translate_fields `list()` of the fields to translate to translate or remove (if `~` present).
    @param variant `list(str())` of regular expression to the BOM variant of each file in `in_file`.
    @param dist_list `list(str())` to be scraped, if empty will be scraped with all distributors
    modules. If `None`, no web/local distributors will be scraped.
    @param collapse_refs `bool()` Collapse or not the designator references in the spreadsheet.
    Default `True`.
    @param suppress_cat_url `bool()` Suppress the distributors catalogue links into the catalogue code in the spreadsheet.
    Default `True`.
    @param currency `str()` Currency in ISO4217. Default 'USD'.
    '''

    # Add or remove field translations, ignore in case the trying to
    # re-translate default field names.
    if translate_fields:
        if len(translate_fields) % 2 == 1:
            raise Exception(
                'Translation fields argument should have an even number of words.'
            )
        for c in range(0, len(translate_fields), 2):
            #field_name_translations.keys(), field_name_translations.values()
            if translate_fields[c] in field_name_translations.values():
                logger.warning(
                    "Not possible re-translate \"{}\" to \"{}\", this is used as internal field names."
                    .format(translate_fields[c].lower(),
                            translate_fields[c + 1].lower()))
                continue
            if translate_fields[c + 1] != '~':
                field_name_translations.update({
                    translate_fields[c].lower():
                    translate_fields[c + 1].lower()
                })
            else:
                field_name_translations.pop(translate_fields[c].lower(), None)

    print("currency: ", currency)
    # Check the integrity of the user personal fields, this should not
    # be any of the reserved fields.
    # This is checked after the translation `dict` is complete, so an
    # before used name field on the translate dictionary can be used
    # user field.
    user_fields = list(set(user_fields))
    for f in user_fields:
        if f.lower() in field_name_translations.keys():
            logger.warning(
                "\"{f}\" field is a reserved field and can not be used user filed. Try to remove it from internal dictionary using `--translate_filed {f} ~`"
                .format(f=f.lower()))
            user_fields.remove(x)

    # Only keep distributors in the included list and not in the excluded list.
    if dist_list != None:
        if not dist_list:
            dist_list = list(distributor_dict.keys())
        if not 'local_template' in dist_list:
            dist_list += ['local_template'
                          ]  # Needed later for creating non-web distributors.
        for d in list(distributor_dict.keys()):
            if not d in dist_list:
                distributor_dict.pop(d, None)
    else:
        for d in list(distributor_dict.keys()):
            distributor_dict.pop(d, None)

    # Deal with some code exception (only one EDA tool or variant
    # informed in the multiple BOM files input).
    if not isinstance(in_file, list):
        in_file = [in_file]
    if not isinstance(variant, list):
        variant = [variant] * len(in_file)
    elif len(variant) != len(in_file):
        variant = [variant[0]] * len(in_file)  #Assume the first as default.
    if not isinstance(eda_name, list):
        eda_name = [eda_name] * len(in_file)
    elif len(eda_name) != len(in_file):
        eda_name = [eda_name[0]] * len(in_file)  #Assume the first as default.

    # Get groups of identical parts.
    parts = dict()
    prj_info = list()
    for i_prj in range(len(in_file)):
        eda_module = eda_modules[eda_name[i_prj]]
        p, info = eda_module.get_part_groups(in_file[i_prj], ignore_fields,
                                             variant[i_prj])
        p = subpartqty_split(p)
        # In the case of multiple BOM files, add the project prefix identifier
        # to each reference/designator. Use the field 'manf#_qty' to control
        # each quantity goes to each project creating a `list()` with length
        # of number of BOM files. This vector will be used in the `group_parts()`
        # to create groups with elements of same 'manf#' that came for different
        # projects.
        if len(in_file) > 1:
            logger.log(
                DEBUG_OVERVIEW,
                'Multi BOMs detected, attaching project identification to references...'
            )
            qty_base = ['0'] * len(in_file)  # Base zero quantity vector.
            for p_ref in list(p.keys()):
                try:
                    qty_base[i_prj] = p[p_ref]['manf#_qty']
                except:
                    qty_base[i_prj] = '1'
                p[p_ref]['manf#_qty'] = qty_base.copy()
                p[PRJ_STR_DECLARE + str(i_prj) + PRJPART_SPRTR +
                  p_ref] = p.pop(p_ref)
        parts.update(p.copy())
        prj_info.append(info.copy())

    # Group part out of the module to be possible to merge different
    # project lists, ignore some field to merge given in the `group_fields`.
    FIELDS_SPREADSHEET = [
        'refs', 'value', 'desc', 'footprint', 'manf', 'manf#'
    ]
    FIELDS_MANFCAT = ([d + '#' for d in distributor_dict] + ['manf#'])
    FIELDS_MANFQTY = ([d + '#_qty' for d in distributor_dict] + ['manf#_qty'])
    FIELDS_IGNORE = FIELDS_SPREADSHEET + FIELDS_MANFCAT + FIELDS_MANFQTY + user_fields + [
        'pricing'
    ]
    for ref, fields in list(parts.items()):
        for f in fields:
            # Merge all extra fields that read on the files that will
            # not be displayed (Needed to check `user_fields`).
            if f not in FIELDS_IGNORE and SEPRTR not in f and not f in group_fields:
                # Not include repetitive field names or fields with the separator `:` defined on `SEPRTR`.
                group_fields += [f]

    # Some fields to be merged on specific EDA are enrolled bellow.
    if 'kicad' in eda_name:
        group_fields += [
            'libpart'
        ]  # This field may be a mess on multiple sheet designs.
    if len(set(eda_name)) > 2:
        # If more than one EDA software was used, ignore the 'footprint'
        # field, because they could have different libraries names.
        group_fields += ['footprint']
    group_fields += ['desc', 'var']  # Always ignore 'desc' ('description')
    # and 'var' ('variant') fields, merging
    # the components in groups.
    group_fields = set(group_fields)
    parts = group_parts(parts, group_fields)

    # If do not have the manufacture code 'manf#' and just distributors codes,
    # check if is asked to scrape a distributor that do not have any code in the
    # parts so, exclude this distributors for the scrap list. This decrease the
    # warning messages given during the process.
    all_fields = []
    for p in parts:
        all_fields += list(p.fields.keys())
    all_fields = set(all_fields)
    if not 'manf#' in all_fields:
        dist_not_rmv = [
            d for d in distributor_dict.keys() if d + '#' in all_fields
        ]
        dist_not_rmv += ['local_template'
                         ]  # Needed later for creating non-web distributors.
        #distributor_scrap = {d:distributor_dict[d] for d in dist_not_rmv}
        distributors = distributor_dict.copy().keys()
        for d in distributors:
            if not d in dist_not_rmv:
                logger.warning(
                    "No 'manf#' and '%s#' field in any part: no information by '%s'.",
                    d, distributor_dict[d]['label']['name'])
                distributor_dict.pop(d, None)

    if logger.isEnabledFor(DEBUG_DETAILED):
        pprint.pprint(distributor_dict)

    # Get the distributor pricing/qty/etc for each part.
    if dist_list:
        # Set part info to default blank values for all the distributors.
        for part in parts:  ## TODO create this for just the current active distributor inside each module.
            # These bellow variable are all the data the each distributor/local API/scrap module needs to fill.
            part.part_num = {dist: ''
                             for dist in dist_list
                             }  # Distributor catalogue number.
            part.url = {dist: ''
                        for dist in dist_list
                        }  # Purchase distributor URL for the specific part.
            part.price_tiers = {
                dist: {}
                for dist in dist_list
            }  # Price break tiers; [[qty1, price1][qty2, price2]...]
            part.qty_avail = {dist: None
                              for dist in dist_list}  # Available quantity.
            part.qty_increment = {dist: None for dist in dist_list}
            part.info_dist = {dist: {} for dist in dist_list}
            part.currency = {dist: DEFAULT_CURRENCY
                             for dist in dist_list}  # Default currency.
            part.moq = {dist: None
                        for dist in dist_list
                        }  # Minimum order quantity allowed by the distributor.
        #distributor.get_dist_parts_info(parts, distributor_dict, dist_list, currency)
        #TODO The calls bellow should became the call above of just one function in the `distributors` package/folder.
        #distributor_class.get_dist_parts_info(parts, distributor_dict, currency) #TODOlocal_template.query_part_info(parts, distributor_dict, currency)
        dist_local_template.query_part_info(parts, distributor_dict, currency)
        api_partinfo_kitspace.query_part_info(parts, distributor_dict,
                                              currency)

    # Create the part pricing spreadsheet.
    create_spreadsheet(parts, prj_info, out_filename, currency, collapse_refs,
                       suppress_cat_url, user_fields,
                       '-'.join(variant) if len(variant) > 1 else variant[0])

    web_dists = sorted([
        d for d in distributor_dict if distributor_dict[d]['type'] != 'local'
    ])
    local_dists = sorted([
        d for d in distributor_dict if distributor_dict[d]['type'] == 'local'
    ])
    dist_list = web_dists + local_dists

    #This section exports some of the parts elements into a JSON file.
    if export_json:
        CURRENCY_ALPHA3 = currency.strip().upper()
        CURRENCY_SYMBOL = numbers.get_currency_symbol(CURRENCY_ALPHA3,
                                                      locale=DEFAULT_LANGUAGE)
        CURRENCY_FORMAT = CURRENCY_SYMBOL + '#,##0.00'

        print("perform json export")
        elements = {
            'conversion?': {},
            'taux': {},
            'currency': {},
            'qty_dispo': {},
            'moq': {},
            'price_tiers': {},
            'qty_increment': {}
        }
        if USE_FULL_JSON:
            elements.update = {
                'url': {},
                'datasheet': {},
                'part_num': {},
            }
        dists_list = {
            'digikey': elements.copy(),
            'farnell': elements.copy(),
            'mouser': elements.copy(),
            'rs': elements.copy()
        }

        #
        dico = dict()
        prices = dict()

        for part in parts:
            #Gather information under each part available:
            dico[part.fields.get('manf#')] = copy.deepcopy(dists_list)
            for dist_s in dists_list.keys():
                if dist_s in dist_list:
                    if USE_FULL_JSON:
                        dico[part.fields.get('manf#')][dist_s][
                            'part_num'] = part.part_num[dist_s]
                        if 'part.datasheet' in locals():
                            dico[part.fields.get(
                                'manf#')][dist_s]['datasheet'] = part.datasheet

                    dico[part.fields.get(
                        'manf#')][dist_s]['url'] = part.url[dist_s]
                    dico[part.fields.get(
                        'manf#')][dist_s]['moq'] = part.moq[dist_s]
                    #print('Getting distributor currency convertion rate {} to {}...', part.currency[dist_s], CURRENCY_ALPHA3)
                    dico[part.fields.get('manf#')][dist_s][
                        'price_tiers'] = part.price_tiers[dist_s]

                    for k, v in dico[part.fields.get(
                            'manf#')][dist_s]['price_tiers'].items():
                        dico[part.fields.get(
                            'manf#')][dist_s]['price_tiers'][k] = round(
                                currency_convert(float(v),
                                                 part.currency[dist_s],
                                                 CURRENCY_ALPHA3), 3)
                    #dico[part.fields.get('manf#')][dist_s]['currency'] = part.currency[dist_s]
                    if dico[part.fields.get('manf#')][dist_s][
                            'currency'] != part.currency[dist_s]:
                        dico[part.fields.get(
                            'manf#')][dist_s]['conversion?'] = "oui"
                        dico[part.fields.get(
                            'manf#')][dist_s]['taux'] = "1 USD = " + str(
                                round(
                                    currency_convert(
                                        float(1.0), part.currency[dist_s],
                                        CURRENCY_ALPHA3), 3)) + " EUR"
                    else:
                        dico[part.fields.get(
                            'manf#')][dist_s]['conversion?'] = "non"
                    dico[part.fields.get(
                        'manf#')][dist_s]['currency'] = CURRENCY_ALPHA3
                    if part.qty_increment[dist_s] == float("inf"):
                        dico[part.fields.get(
                            'manf#')][dist_s]['qty_increment'] = "null"
                    else:
                        dico[part.fields.get('manf#')][dist_s][
                            'qty_increment'] = part.qty_increment[dist_s]
                    dico[part.fields.get(
                        'manf#')][dist_s]['qty_dispo'] = part.qty_avail[dist_s]

        for part in parts:
            for dist_s in dists_list.keys():
                if dist_s not in dist_list:
                    print("delete:", dist_s)
                    del dico[part.fields.get('manf#')][dist_s]
                #print("delete:", dist_s)

        #One the dictionary is completed, call json dump file
        #using the json method.
        print(out_filename)
        json_obj = json.dumps(dico, indent=4)
        with open(os.path.join(out_filename + '.json'), 'w') as fic:
            fic.write(json.dumps(dico, indent=4))

    # Print component groups for debugging purposes.
    if logger.isEnabledFor(DEBUG_DETAILED):
        for part in parts:
            for f in dir(part):
                if f.startswith('__'):
                    continue
                elif f.startswith('html_trees'):
                    continue
                else:
                    print('{} = '.format(f), end=' ')
                    try:
                        pprint.pprint(part.__dict__[f])
                    except TypeError:
                        # Python 2.7 pprint has some problem ordering None and strings.
                        print(part.__dict__[f])
                    except KeyError:
                        pass
            print()
def review_sales_agreement():
    # save case ref in session so that its available on error redirects
    if request.args.get('case_reference'):
        session['case_reference'] = str(request.args.get('case_reference'))

    # form post
    if request.method == 'POST':
        try:
            title_id = request.form['title_id']

            # api to fetch buyer's conveyancer details
            url = current_app.config[
                'CONVEYANCER_API_URL'] + '/titles/' + title_id + '/sales-agreement'
            agreement_res = requests.get(
                url, headers={'Accept': 'application/json'})
            agreement_obj = agreement_res.json()
            agreement_approval_data = {
                "action": "approve",
                "signatory": agreement_obj['buyer_conveyancer']
            }
            # approve agreement api call
            url = current_app.config[
                'CONVEYANCER_API_URL'] + '/titles/' + title_id + '/sales-agreement'
            response = requests.put(url,
                                    data=json.dumps(agreement_approval_data),
                                    headers={
                                        'Accept': 'Application/JSON',
                                        'Content-Type': 'Application/JSON'
                                    })
            if response.status_code == 200:
                return redirect(url_for('conveyancer_admin.case_list'))
            else:
                return redirect(
                    url_for('conveyancer_admin.review_sales_agreement',
                            error_message='Error: ' + response.text))
        except Exception as e:
            return str(e)

    if request.method == 'GET':
        cases_details = {}
        # get case details
        url = current_app.config[
            'CASE_MANAGEMENT_API_URL'] + '/cases/' + session['case_reference']
        case_details_res = requests.get(
            url,
            params={
                "embed":
                "counterparty_id,client,"
                "counterparty_conveyancer_contact_id,assigned_staff"
            },
            headers={'Accept': 'application/json'})
        if case_details_res.status_code == 200:
            cases_details = case_details_res.json()
            # if title number is not updated in the case redirect to case list
            if cases_details['title_number']:
                title_id = cases_details['title_number']
            else:
                return redirect(
                    url_for(
                        'conveyancer_admin.case_list',
                        error_message='Error: Title not found in the case'))

            if cases_details['case_type'] == "sell":
                fetch_case_details("seller", "buyer", cases_details)
            else:
                fetch_case_details("buyer", "seller", cases_details)
        # make API call to fetch agreement values
        url = '{0}/titles/{1}/sales-agreement'.format(
            current_app.config['CONVEYANCER_API_URL'],
            cases_details['title_number'])
        agreement_details_response = requests.get(
            url, headers={'Accept': 'application/json'})

        if agreement_details_response.status_code == 200:
            agreement_detail = agreement_details_response.json()
            obj_date = datetime.strptime(agreement_detail['completion_date'],
                                         '%Y-%m-%dT%H:%M:%S')
            agreement_detail['completion_date'] = datetime.strftime(
                obj_date, '%d %B %Y %H:%M')
            if agreement_detail['latest_update_date']:
                update_date = datetime.strptime(
                    agreement_detail['latest_update_date'],
                    '%Y-%m-%dT%H:%M:%S.%f')
                agreement_detail[
                    'latest_update_date_time'] = datetime.strftime(
                        update_date, '%d/%m/%Y %H:%M:%S')
            else:
                agreement_detail['latest_update_date_time'] = ""

            agreement_detail['purchase_price'] = numbers.format_currency(
                agreement_detail['purchase_price'],
                agreement_detail['purchase_price_currency_code'])
            agreement_detail['deposit'] = numbers.format_currency(
                agreement_detail['deposit'],
                agreement_detail['deposit_currency_code'])
            agreement_detail['balance'] = numbers.format_currency(
                agreement_detail['balance'],
                agreement_detail['balance_currency_code'])
            agreement_detail[
                'deposit_currency_code'] = numbers.get_currency_symbol(
                    agreement_detail['deposit_currency_code'])
            agreement_detail[
                'balance_currency_code'] = numbers.get_currency_symbol(
                    agreement_detail['balance_currency_code'])
            agreement_detail[
                'contents_price_currency_code'] = numbers.get_currency_symbol(
                    agreement_detail['contents_price_currency_code'])
            agreement_detail[
                'purchase_price_currency_code'] = numbers.get_currency_symbol(
                    agreement_detail['purchase_price_currency_code'])
            return render_template('app/admin/review_sales_agreement.html',
                                   agreement_details=agreement_detail,
                                   title_details=cases_details,
                                   title_id=title_id,
                                   admin=True)
        else:
            return render_template(
                'app/admin/review_sales_agreement.html',
                error_message="Title agreement does not exist",
                admin=True)
Beispiel #40
0
def display_currency(currency, request):
    return get_currency_symbol(currency, locale=get_locale(request))
Beispiel #41
0
def format_currency(value):
    return numbers.format_currency(
            float(value),
            numbers.get_currency_symbol('USD', 'en_US'),
            u'\xa4\xa4 #,##0.00', locale='pt_BR')
Beispiel #42
0
    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)
Beispiel #43
0
    def get(self, request, *args, **kwargs):
        db.reset_queries()
        if request.method == "POST":
            data = request.POST
        else:
            data = request.GET

        view = 'heat'
        center = None
        zoom = 4
        mapTypeId = None

        if data.has_key('view'):
            view = data.get('view')
        if data.has_key('center'):
            c = data.get('center').split(',')
            center = maps.LatLng(c[0], c[1])
        if data.has_key('zoom'):
            zoom = int(data.get('zoom'))
        if data.has_key('mapTypeId'):
            mapTypeId = data.get('mapTypeId')



        if data.has_key('concentration'):
            view = 'concentration'
        gmap = self.get_map(request, center, zoom, mapTypeId)

        sql_columns = """
        a.location_id, 
			a.entity_id,
			sum(c.amount_usd) sum_ammount,
			d.polygon
        """

        if view == 'concentration':
            sql_columns = " min(amount_usd), max(amount_usd) "


        sql = "SELECT 	" + sql_columns + """
FROM ecofunds_entity_locations a
INNER JOIN ecofunds_entities  b ON (a.entity_id = b.entity_id) 
INNER JOIN ecofunds_investments c ON  c.recipient_entity_id = b.entity_id
INNER JOIN ecofunds_locations d ON d.id = a.location_id
inner join ecofunds_countries cou on cou.id = d.country_id
WHERE b.validated = 1
"""

        query_params = []
        if data.has_key('s_project_name') and data['s_project_name'] != '':
            sql+=" and b.title like %s "
            query_params.append('%' + data['s_project_name'] + '%')
        if data.has_key('s_project_activity_type') and data['s_project_activity_type']!='':
            sql+=" and exists (select 1 from ecofunds_entity_activities e where e.entity_id = b.entity_id and e.activity_id = %s) "
            query_params.append(data['s_project_activity_type'])

        if data.has_key('s_organization') and data['s_organization'] != '':
            sql+=' and exists (select 1 from ecofunds_organization f where f.id in (c.recipient_organization_id, c.funding_organization_id) and {fn concat(f.name, f.acronym)} like %s) '
            query_params.append('%' + data['s_organization'] + '%')


        if data.has_key('s_organization_type') and data['s_organization_type'] != '':
            sql+=' and exists (select 1 from ecofunds_organization f where f.id in (c.recipient_organization_id, c.funding_organization_id) and f.type_id like %s) '
            query_params.append('%' + data['s_organization_type'] + '%')

        
        if data.has_key('s_country') and data['s_country'] != '':
            sql+=" and cou.name like %s "
            query_params.append('%'+data['s_country'] + '%')

        if data.has_key('s_state') and data['s_state'] != '':
            sql+=" and (d.iso_sub = %s or d.name like %s) "
            query_params.append(data['s_state'])
            query_params.append('%'+data['s_state']+'%')


        
        if data.has_key('s_investment_type') and data['s_investment_type'] != '':
            sql+= " and c.type_id = %s "
            query_params.append(data['s_investment_type'])


        if data.has_key('s_investment_date_from') and data['s_investment_date_from'] != '':
            dt_from = trans_date(data['s_investment_date_from'])
            if dt_from:
                sql+= " and c.created_at >= %s "
                query_params.append(dt_from)


        if data.has_key('s_investment_date_to') and data['s_investment_date_to'] != '':
            dt_to = trans_date(data['s_investment_date_to'])
            if dt_to:
                sql+= " and c.created_at <= %s "
                query_params.append(dt_to)
            

        if view != 'concentration':
            sql+=" group by a.location_id, a.entity_id "

            min_invest = 0
            max_invest = 99999999
            if data.has_key('s_investments_from') and data['s_investments_from'] != '':
                min_invest = float(data['s_investments_from'])
            if data.has_key('s_investments_to') and data['s_investments_to']:
                max_invest = float(data['s_investments_to'])
            if max_invest == 0:
                max_invest = 99999999
            if min_invest > max_invest:
                min_invest, max_invest = max_invest, min_invest
            if min_invest > 0 or max_invest < 99999999:
                sql+= ' having sum_ammount between %s and %s '
                query_params.append(min_invest)
                query_params.append(max_invest)



        cursor = db.connection.cursor()
        cursor.execute(sql, query_params)
       
        #list = ProjectData.locationFilteredList(request)
            

        if view == 'concentration':
            start, end = 0, 0
            for item in cursor.fetchall():
                if not (item[0] is None):
                    start = float(item[0])
                    end = float(item[1])
            json = {'start': format_currency(start), 'end': format_currency(end)}
            return http.HttpResponse(dumps(json, cls=DjangoJSONEncoder), content_type='application/json')

        points = {}
        

        for item in cursor.fetchall():
            location_id = item[0]
            entity_id = item[1]
            amount = item[2]
            xml = BeautifulSoup(item[3])

            key = 'pos'+str(location_id)            

            if not points.has_key(key):
                paths = []
                
                for polygon in xml.findAll('polygon'):
                    corners = []
                    latlngs = []
                    coordinates = polygon.outerboundaryis.linearring.coordinates.text.split(' ')
                    
                    for c in coordinates:
                        
                        o = c.split(',')
                        cx = float(o[1])
                        cy = float(o[0])
                        corners.append((cx, cy))
                        latlngs.append(maps.LatLng(cx, cy))

                    x, y = self.polygon_centroid(corners)
                    paths.append(latlngs)

                    
                points[key] = {'centroid': maps.LatLng(x, y), 'paths': paths, 'investment': 0, 'projects': [{'id': entity_id, 'amount': amount}]}
            else:
                b= False
                for p in points[key]['projects']:
                    if p['id'] == entity_id:
                        b = True
                if not b:
                    points[key]['projects'].append({'id': entity_id, 'amount': amount})

        for key in points:
            for o in points[key]['projects']:
                points[key]['investment'] += o['amount']

        if len(points) > 0:
            sum_inv = sum(points[key]['investment'] for key in points)
            max_inv = max(points[key]['investment'] for key in points)
            min_inv = min(points[key]['investment'] for key in points)

            if view == 'bubble':

                for key in points:
                    amount = points[key]['investment']
                    scale = 5 * int(math.floor(((amount-min_inv)/(max_inv-min_inv))*10)+1)

                    marker = maps.Marker(opts = {
                        'map': gmap,
                        'position': points[key]['centroid'],
                        'icon': {
                            'path': SymbolPath.CIRCLE,
                            'fillOpacity': 0.7,
                            'fillColor': '#FFFFFF',
                            'strokeOpacity': 1.0,
                            'strokeColor': '#00539f',
                            'strokeWeight': 1, 
                            'scale': scale
                        }
                    })

                    #t = loader.get_template('maps/info-bubble.html')
                    #c = Context({ 'org': org })
                
                    info = InfoBubble({
                        'content': 'teste',#t.render(c),
                        'disableAutoPan': True,
                        'backgroundColor': '#FFF',
                        'borderRadius': 10,
                        'borderWidth': 0,
                        'padding': 0,
                        'minHeight': 40,
                        'minWidth': 400,
                        'maxWidth': 400,
                        'shadowStyle': 1,
                        'arrowPosition':10,
                        'hideCloseButton': True,
                    })
                    info.open(gmap, marker)

            elif view == 'density':
            
                for key in points:
                    amount = points[key]['investment']
                    text = numbers.format_currency(
                            float(amount),
                            numbers.get_currency_symbol('USD', 'en_US'),
                            u'\xa4\xa4 #,##0.00', locale=request.LANGUAGE_CODE.replace('-', '_')
                        )
                    scale = (len(text)+1) * 3

                    marker = maps.Marker(opts = {
                        'map': gmap,
                        'position': points[key]['centroid'],
                        'icon': {
                            'path': SymbolPath.CIRCLE,
                            'fillOpacity': 0.8,
                            'fillColor': '#8eb737',
                            'strokeWeight': 0, 
                            'scale': scale
                        }
                    })

                    label = Label(opts={
                        'map': gmap,
                        'position': points[key]['centroid'],
                        'text': text
                    })

            elif view == 'heat':

                fill_colors = ['#28B9D4', '#7CC22C', '#ECCE0A', '#ED8A09', '#ED0B0C']
                for key in points:
                    amount = points[key]['investment']
                    #scale = int(math.floor((((amount-min_inv)/(max_inv-min_inv))*10)/2)-1)
                    if min_inv == max_inv:
                        scale = 1.0
                    else:
                        scale = round( float(amount-min_inv)/float(max_inv-min_inv), 2)


                    tp = pylab.cm.RdYlGn(1 - scale)
                    rgb = []
                    for c in tp[:3]:
                        rgb.append(c * 255)

                    h = '#%02X%02X%02X' % (rgb[0], rgb[1], rgb[2])

                    polygon = maps.Polygon(opts = {
                        'map': gmap,
                        'paths': points[key]['paths'],
                        'strokeWeight': 0.8,
                        'strokeColor': h,
                        'fillColor':  h,
                        'fillOpacity': 0.5
                    })
                    maps.event.addListener(polygon, 'mouseover', 'ecofundsMap.polygonOver')
                    maps.event.addListener(polygon, 'mouseout', 'ecofundsMap.polygonOut')


        

        return http.HttpResponse(dumps(gmap, cls=DjangoJSONEncoder), content_type='application/json')
Beispiel #44
0
def test_get_currency_symbol():
    assert numbers.get_currency_symbol('USD', 'en_US') == u'$'
Beispiel #45
0
    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)
        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': unicode(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(unicode(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 = urllib.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 univerity 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_escaped,
            "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,
        }
        context.update(
            get_experiment_user_metadata_context(
                course,
                request.user,
            )
        )

        title_content = _("Congratulations!  You are now enrolled in {course_name}").format(
            course_name=course.display_name_with_default_escaped
        )

        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()
            ]
            context["currency"] = verified_mode.currency.upper()
            context["currency_symbol"] = get_currency_symbol(verified_mode.currency.upper())
            context["min_price"] = verified_mode.min_price
            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)