2 Functions for handling splitting expenditures between people
5 from bluechips import model
6 from bluechips.model.meta import Session
7 from bluechips.lib.helpers import round_currency
8 from decimal import Decimal
13 Split up an expenditure evenly among the resident users
15 e should be a bluechips.model:Expenditure object
18 residents = Session.query(model.User).filter(model.User.resident==True)
19 split_percentage = Decimal(100) / Decimal(residents.count())
20 split(e, dict((resident, split_percentage) for resident in residents))
22 def split(e, split_dict):
24 Split up an expenditure.
26 e should be a bluechips.model:Expenditure object.
28 split_dict should be a dict mapping from bluechips.model:User
29 objects to a decimal:Decimal object representing the percentage
30 that user is responsible for.
32 Percentages will be normalized to sum to 100%.
34 If the split leaks or gains money due to rounding errors, the
35 pennies will be randomly distributed to one of the users.
37 I mean, come on. You're already living together. Are you really
38 going to squabble over a few pennies?
41 map(Session.delete, Session.query(model.Split))
43 total = sum(split_dict.itervalues())
45 for user, share in split_dict.iteritems():
46 split_dict[user] = share / total
50 for user, share in split_dict.iteritems():
51 amounts_dict[user] = round_currency(split_dict[user] * e.amount)
53 difference = e.amount - sum(amounts_dict.itervalues())
56 for i in xrange(difference * 100):
57 winner = random.choice(amounts_dict.keys())
58 amounts_dict[winner] += Decimal('0.01')
60 for i in xrange(difference * -100):
61 winner = random.choice(amounts_dict.keys())
62 amounts_dict[winner] -= Decimal('0.01')
64 for user, share in amounts_dict.iteritems():
71 __all__ = ['split', 'even_split']