X-Git-Url: https://asedeno.scripts.mit.edu/gitweb/?a=blobdiff_plain;ds=sidebyside;f=bluechips%2Fmodel%2Ftypes.py;h=fdd3b8bd4c6ce1c622960c0df02827a4965427c3;hb=cef3f80d9d9a7a08b8c09bc909cb52afbdb0f0d2;hp=d4454813bd7e5463fc513518359b755b53abd25f;hpb=ac41cefa3569ceca9ebee894d2c333360b4158fc;p=bluechips.git diff --git a/bluechips/model/types.py b/bluechips/model/types.py index d445481..fdd3b8b 100644 --- a/bluechips/model/types.py +++ b/bluechips/model/types.py @@ -2,11 +2,59 @@ Define special types used in BlueChips """ +import locale +from decimal import Decimal, InvalidOperation + import sqlalchemy as sa +from formencode import validators, Invalid from bluechips.lib.subclass import SmartSubclass from weakref import WeakValueDictionary +def localeconv(): + "Manually install en_US for systems that don't have it." + d = {'currency_symbol': '$', + 'decimal_point': '.', + 'frac_digits': 2, + 'grouping': [3, 3, 0], + 'int_curr_symbol': 'USD ', + 'int_frac_digits': 2, + 'mon_decimal_point': '.', + 'mon_grouping': [3, 3, 0], + 'mon_thousands_sep': ',', + 'n_cs_precedes': 1, + 'n_sep_by_space': 0, + 'n_sign_posn': 1, + 'negative_sign': '-', + 'p_cs_precedes': 1, + 'p_sep_by_space': 0, + 'p_sign_posn': 1, + 'positive_sign': '', + 'thousands_sep': ','} + return d +locale.localeconv = localeconv + + +class CurrencyValidator(validators.FancyValidator): + "A validator to convert to Currency objects." + messages = {'amount': "Please enter a valid currency amount", + 'precision': "Only two digits after the decimal, please"} + + def _to_python(self, value, state): + try: + dec = Decimal(value) + except InvalidOperation: + raise Invalid(self.message('amount', state), + value, state) + else: + ret = dec.quantize(Decimal('1.00')) + if ret != dec: + raise Invalid(self.message('precision', state), + value, state) + else: + return Currency(int(ret * 100)) + + class Currency(object): """ Store currency values as an integral number of cents @@ -80,10 +128,8 @@ class Currency(object): def __repr__(self): return '%s("%s")' % (self.__class__.__name__, str(self)) def __str__(self): - sign = '-' if self.value < 0 else '' - cents = abs(self.value) % 100 - dollars = (abs(self.value) - cents) / 100 - return '%s$%s.%.02d' % (sign, dollars, cents) + return locale.currency(self.value / 100., grouping=True) + class DBCurrency(sa.types.TypeDecorator): """