]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/lib/totals.py
7a3c3a7504af44136e78e3b3b839aa71f472953e
[bluechips.git] / bluechips / lib / totals.py
1 """
2 Calculate the total state of the books
3 """
4
5 from bluechips import model
6 from bluechips.model.meta import Session
7
8 import sqlalchemy
9
10 from decimal import Decimal
11
12 def debts():
13     # In this scheme, negative numbers represent money the house owes
14     # the user, and positive numbers represent money the user owes the
15     # house
16     users = Session.query(model.User)
17     
18     debts = {}
19     
20     # First, credit everyone for expenditures they've made
21     for user in users:
22         debts[user] = -sum(map((lambda x: x.amount), user.expenditures))
23     
24     # Next, debit everyone for expenditures that they have an
25     # investment in (i.e. splits)
26     
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)
30     
31     for split, total_cents in total_splits:
32         debts[split.user] += (total_cents / 100)
33     
34     # Finally, move transfers around appropriately
35     #
36     # To keep this from getting to be expensive, have SQL sum up
37     # transfers for us
38     
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)
43     
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
48     
49     return debts