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
8 class Expenditure(object):
10 return '<Expenditure: spender: %s spent: %s>' % (self.spender,
15 Split up an expenditure evenly among the resident users
18 residents = meta.Session.query(User).filter(User.resident==True)
19 split_percentage = Decimal(100) / Decimal(residents.count())
20 self.split(dict((resident, split_percentage) for resident in residents))
22 def split(self, split_dict):
24 Split up an expenditure.
26 split_dict should be a dict mapping from bluechips.model:User
27 objects to a decimal:Decimal object representing the percentage
28 that user is responsible for.
30 Percentages will be normalized to sum to 100%.
32 If the split leaks or gains money due to rounding errors, the
33 pennies will be randomly distributed to one of the users.
35 I mean, come on. You're already living together. Are you really
36 going to squabble over a few pennies?
39 map(meta.Session.delete, meta.Session.query(Split).\
40 filter_by(expenditure_id=self.id))
42 total = sum(split_dict.itervalues())
44 for user, share in split_dict.iteritems():
45 split_dict[user] = share / total
49 for user, share in split_dict.iteritems():
50 amounts_dict[user] = Currency(split_dict[user] * self.amount)
52 difference = self.amount - sum(amounts_dict.itervalues())
55 for i in xrange(difference):
56 winner = random.choice(amounts_dict.keys())
57 amounts_dict[winner] += Currency(1)
59 for i in xrange(difference):
60 winner = random.choice(amounts_dict.keys())
61 amounts_dict[winner] -= Currency(1)
63 for user, share in amounts_dict.iteritems():
64 s = Split(self, user, share)
67 __all__ = ['Expenditure']