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
13 # In this scheme, negative numbers represent money the house owes
14 # the user, and positive numbers represent money the user owes the
16 users = Session.query(model.User)
20 # First, credit everyone for expenditures they've made
22 debts[user] = -sum(map((lambda x: x.amount), user.expenditures))
24 # Next, debit everyone for expenditures that they have an
25 # investment in (i.e. splits)
27 total_splits = Session.query(model.Split).\
28 add_column(sqlalchemy.func.sum(model.Split.share), 'total_split').\
29 group_by(model.Split.user_id)
31 for split, total_cents in total_splits:
32 debts[split.user] += (total_cents / 100)
34 # Finally, move transfers around appropriately
36 # To keep this from getting to be expensive, have SQL sum up
39 transfer_q = Session.query(model.Transfer).\
40 add_column(sqlalchemy.func.sum(model.Transfer.amount), 'total_amount')
41 total_debits = transfer_q.group_by(model.Transfer.debtor_id)
42 total_credits = transfer_q.group_by(model.Transfer.creditor_id)
44 for transfer, total_amount in total_debits:
45 debts[transfer.debtor] -= total_amount
46 for transfer, total_amount in total_credits:
47 debts[transfer.creditor] += total_amount