X-Git-Url: https://asedeno.scripts.mit.edu/gitweb/?a=blobdiff_plain;ds=sidebyside;f=bluechips%2Fmodel%2Ftypes.py;h=1c54e764fb91e4d6907f68575cab22ffb6f59b17;hb=3b864c81e804769f2be45b38c319895d1735aef9;hp=a81a8ae6ce09db566aaf395d0341c6ef7c6b0055;hpb=9bff8b8b19f3579d1ff654255e98826e7340a40e;p=bluechips.git diff --git a/bluechips/model/types.py b/bluechips/model/types.py index a81a8ae..1c54e76 100644 --- a/bluechips/model/types.py +++ b/bluechips/model/types.py @@ -3,10 +3,46 @@ Define special types used in BlueChips """ import sqlalchemy as sa -from bluechips.lib.helpers import round_currency -from decimal import Decimal +from bluechips.lib.subclass import SmartSubclass -class Currency(sa.types.TypeDecorator): +class Currency(object): + __metaclass__ = SmartSubclass(int) + def __init__(self, value): + if isinstance(value, str): + self.value = int(float(value) * 100) + else: + self.value = int(value) + + def __int__(self): + return self.value + def __float__(self): + return float(self.value) + def __long__(self): + return long(self.value) + + def __cmp__(self, other): + try: + return self.value.__cmp__(int(other)) + except: + return self.value.__cmp__(0) + + def __mul__(self, other): + return Currency(self.value * other) + def __rmul__(self, other): + return self.__mul__(other) + + def __str_no_dollar__(self): + return str(self)[1:] + + 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) + +class DBCurrency(sa.types.TypeDecorator): """ A type which represents monetary amounts internally as integers. @@ -16,7 +52,7 @@ class Currency(sa.types.TypeDecorator): impl = sa.types.Integer def process_bind_param(self, value, engine): - return int(value * 100) + return int(value) def convert_result_value(self, value, engine): - return round_currency(Decimal(value) / 100) + return Currency(value)