2 Calculate the total state of the books
5 from bluechips import model
6 from bluechips.model.meta import Session
10 from decimal import Decimal
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 = Session.query(model.User)
26 # First, credit everyone for expenditures they've made
28 debts[user] = -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 = Session.query(model.Split).\
34 add_column(sqlalchemy.func.sum(model.Split.share), 'total_split').\
35 group_by(model.Split.user_id)
37 for split, total_cents in total_splits:
38 debts[split.user] += (total_cents / 100)
40 # Finally, move transfers around appropriately
42 # To keep this from getting to be expensive, have SQL sum up
45 transfer_q = Session.query(model.Transfer).\
46 add_column(sqlalchemy.func.sum(model.Transfer.amount), '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[transfer.debtor] -= total_amount
52 for transfer, total_amount in total_credits:
53 debts[transfer.creditor] += total_amount
58 # This algorithm has been shamelessly stolen from Nelson Elhage's
59 # <nelhage@mit.edu> implementation for our 2008 summer apartment.
62 debts_list = [dict(who=user, amount=amount) for user, amount in \
63 debts_dict.iteritems()]
64 debts_list.sort(reverse=True, key=(lambda x: abs(x['amount'])))
66 owes_list = [debt for debt in debts_list if debt['amount'] > 0]
67 owed_list = [debt for debt in debts_list if debt['amount'] < 0]
71 while len(owes_list) > 0 and len(owed_list) > 0:
75 sum = owes['amount'] + owed['amount']
82 # person in owes still owes money
83 owes['amount'] += owed['amount']
87 # person in owed is owed more than owes has to give
88 owed['amount'] += owes['amount']
92 settle.append((owes['who'], owed['who'], val))
94 if len(owes_list) > 0:
95 raise DirtyBooks, ("People still owe money", owes_list)
96 if len(owed_list) > 0:
97 raise DirtyBooks, ("People are still owed money", owed_list)