2 Calculate the total state of the books
5 from bluechips import model
6 from bluechips.model import meta
8 from bluechips.model.types import Currency
12 class DirtyBooks(Exception):
14 If the books don't work out, raise this
19 # In this scheme, negative numbers represent money the house owes
20 # the user, and positive numbers represent money the user owes the
22 users = meta.Session.query(model.User)
26 # First, credit everyone for expenditures they've made
28 debts_dict[user] = Currency(-sum(map((lambda x: x.amount), user.expenditures)))
30 # Next, debit everyone for expenditures that they have an
31 # investment in (i.e. splits)
33 total_splits = meta.Session.query(model.Split).\
34 add_column(sqlalchemy.func.sum(model.Split.share).label('total_split')).\
35 group_by(model.Split.user_id)
37 for split, total_cents in total_splits:
38 debts_dict[split.user] += total_cents
40 # Finally, move transfers around appropriately
42 # To keep this from getting to be expensive, have SQL sum up
45 transfer_q = meta.Session.query(model.Transfer).\
46 add_column(sqlalchemy.func.sum(model.Transfer.amount).label('total_amount'))
47 total_debits = transfer_q.group_by(model.Transfer.debtor_id)
48 total_credits = transfer_q.group_by(model.Transfer.creditor_id)
50 for transfer, total_amount in total_debits:
51 debts_dict[transfer.debtor] -= total_amount
52 for transfer, total_amount in total_credits:
53 debts_dict[transfer.creditor] += total_amount
57 def settle(debts_dict):
58 # This algorithm has been shamelessly stolen from Nelson Elhage's
59 # <nelhage@mit.edu> implementation for our 2008 summer apartment.
61 debts_list = [dict(who=user, amount=amount) for user, amount in \
62 debts_dict.iteritems()]
63 #debts_list.sort(reverse=True, key=(lambda x: abs(x['amount'])))
65 owes_list = [debt for debt in debts_list if debt['amount'] > 0]
66 owed_list = [debt for debt in debts_list if debt['amount'] < 0]
70 while len(owes_list) > 0 and len(owed_list) > 0:
71 owes_list.sort(reverse=True, key=(lambda x: abs(x['amount'])))
72 owed_list.sort(reverse=True, key=(lambda x: abs(x['amount'])))
77 sum = owes['amount'] + owed['amount']
84 # person in owes still owes money
85 owes['amount'] += owed['amount']
89 # person in owed is owed more than owes has to give
90 owed['amount'] += owes['amount']
94 settle_list.append((owes['who'], owed['who'], val))
96 if len(owes_list) > 0:
97 raise DirtyBooks, ("People still owe money", owes_list)
98 if len(owed_list) > 0:
99 raise DirtyBooks, ("People are still owed money", owed_list)
103 __all__ = ['debts', 'settle']