]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/controllers/status.py
little performance tweaks
[bluechips.git] / bluechips / controllers / status.py
1 """
2 Calculate the current state of the books
3 """
4
5 import logging
6
7 from bluechips.lib.base import *
8 from bluechips.lib.totals import *
9
10 import sqlalchemy
11 from sqlalchemy import orm
12
13 from datetime import date, timedelta
14
15 from bluechips.model.types import Currency
16
17 from pylons import request
18
19 log = logging.getLogger(__name__)
20
21 class StatusController(BaseController):
22     def index(self):
23         c.debts = debts()
24         c.settle = settle(c.debts)
25         
26         c.total = self._total()
27         
28         year = date.today() - timedelta(days=365)
29         this_year = date.today().replace(month=1, day=1)
30         this_month = date.today().replace(day=1)
31         last_month = (date.today() - timedelta(days=30)).replace(day=1)
32         
33         c.year_total, c.this_year_total, c.this_month_total = \
34             [self._total(model.Expenditure.date >= i)
35              for i in [year, this_year, this_month]]
36         
37
38         c.last_month_total = self._total(sqlalchemy.and_(
39                     model.Expenditure.date >= last_month,
40                     model.Expenditure.date < this_month))
41         
42         c.expenditures = meta.Session.query(model.Expenditure).\
43                 filter(sqlalchemy.or_(
44                     model.Expenditure.spender == request.environ['user'],
45                     model.Expenditure.splits.any(
46                         sqlalchemy.and_(
47                             model.Split.user == request.environ['user'],
48                             model.Split.share != 0)))).\
49                 options(orm.eagerload('splits')).\
50                 limit(10).all()
51         c.transfers = meta.Session.query(model.Transfer).\
52             filter(sqlalchemy.or_(
53                 model.Transfer.debtor==request.environ['user'],
54                 model.Transfer.creditor==request.environ['user'])).\
55                 limit(10).all()
56         
57         return render('/status/index.mako')
58     
59     def _total(self, conditions=None):
60         q = meta.Session.query(sqlalchemy.func.SUM(
61             model.Expenditure.amount))
62         if conditions is not None:
63             q = q.filter(conditions)
64         return q.scalar()