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).\
42 filter_by(expenditure_id=e.id))
44 total = sum(split_dict.itervalues())
46 for user, share in split_dict.iteritems():
47 split_dict[user] = share / total
51 for user, share in split_dict.iteritems():
52 amounts_dict[user] = round_currency(split_dict[user] * e.amount)
54 difference = e.amount - sum(amounts_dict.itervalues())
57 for i in xrange(difference * 100):
58 winner = random.choice(amounts_dict.keys())
59 amounts_dict[winner] += Decimal('0.01')
61 for i in xrange(difference * -100):
62 winner = random.choice(amounts_dict.keys())
63 amounts_dict[winner] -= Decimal('0.01')
65 for user, share in amounts_dict.iteritems():
72 __all__ = ['split', 'even_split']