1 from bluechips.model.user import User
2 from bluechips.model.split import Split
3 from bluechips.model import meta
4 from bluechips.model.types import Currency
5 from decimal import Decimal
6 from datetime import datetime
9 class Expenditure(object):
10 def __init__(self, spender=None, amount=Currency(0), description=u"",
12 self.spender = spender
14 self.description = description
16 self.date = datetime.now()
19 return '<Expenditure: spender: %s spent: %s>' % (self.spender,
24 Split up an expenditure evenly among the resident users
27 residents = meta.Session.query(User).filter(User.resident==True)
28 split_percentage = Decimal(100) / Decimal(residents.count())
29 self.split(dict((resident, split_percentage) for resident in residents))
31 def split(self, split_dict):
33 Split up an expenditure.
35 split_dict should be a dict mapping from bluechips.model:User
36 objects to a decimal:Decimal object representing the percentage
37 that user is responsible for.
39 Percentages will be normalized to sum to 100%.
41 If the split leaks or gains money due to rounding errors, the
42 pennies will be randomly distributed to one of the users.
44 I mean, come on. You're already living together. Are you really
45 going to squabble over a few pennies?
48 map(meta.Session.delete, meta.Session.query(Split).\
49 filter_by(expenditure_id=self.id))
51 total = sum(split_dict.itervalues())
53 for user, share in split_dict.items():
59 for user, share in split_dict.iteritems():
60 amounts_dict[user] = Currency((share * self.amount) / total)
62 difference = self.amount - sum(amounts_dict.itervalues())
65 for i in xrange(difference):
66 winner = random.choice(amounts_dict.keys())
67 amounts_dict[winner] += Currency(1)
69 for i in xrange(-difference):
70 winner = random.choice(amounts_dict.keys())
71 amounts_dict[winner] -= Currency(1)
73 for user, share in amounts_dict.iteritems():
74 s = Split(self, user, share)
77 def involves(self, user):
78 "Returns True if ``user`` is involved in this expenditure."
79 return (any((split.user == user) and (split.share != 0)
80 for split in self.splits) or
81 (self.spender == user))
83 def share(self, user):
84 "Return the share corresponding to ``user``."
85 shares = dict((split.user, split.share)
86 for split in self.splits)
87 return shares.get(user, Currency(0))
89 __all__ = ['Expenditure']