]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/controllers/spend.py
ripped out toscawidgets, replaced with formencode, put split editing on main expendit...
[bluechips.git] / bluechips / controllers / spend.py
1 """
2 Handle expenditures
3 """
4
5 import logging
6
7 from decimal import Decimal, InvalidOperation
8
9 from bluechips.lib.base import *
10
11 from pylons import request
12 from pylons.decorators.rest import dispatch_on
13 from pylons.decorators import validate
14
15 from formencode import validators, Schema
16 from formencode.foreach import ForEach
17 from formencode.variabledecode import NestedVariables
18
19 log = logging.getLogger(__name__)
20
21
22 class ShareSchema(Schema):
23     "Validate individual user shares."
24     allow_extra_fields = False
25     user_id = validators.Int(not_empty=True)
26     amount = validators.Number(not_empty=True)
27
28
29 class ExpenditureSchema(Schema):
30     "Validate an expenditure."
31     allow_extra_fields = False
32     pre_validators = [NestedVariables()]
33     spender_id = validators.Int(not_empty=True)
34     amount = validators.Number(not_empty=True)
35     description = validators.UnicodeString()
36     date = validators.DateConverter()
37     shares = ForEach(ShareSchema)
38     
39
40 class SpendController(BaseController):
41     def index(self):
42         return self.edit()
43     
44     def edit(self, id=None):
45         c.users = meta.Session.query(model.User.id, model.User)
46         if id is None:
47             c.title = 'Add a New Expenditure'
48             c.expenditure = model.Expenditure()
49             c.expenditure.spender_id = request.environ['user'].id
50         else:
51             c.title = 'Edit an Expenditure'
52             c.expenditure = meta.Session.query(model.Expenditure).get(id)
53         return render('/spend/index.mako')
54
55     @validate(schema=ExpenditureSchema(), form='edit', variable_decode=True)
56     def update(self, id=None):
57         # Either create a new object, or, if we're editing, get the
58         # old one
59         if id is None:
60             e = model.Expenditure()
61             meta.Session.add(e)
62         else:
63             e = meta.Session.query(model.Expenditure).get(id)
64         
65         # Set the fields that were submitted
66         shares = self.form_result.pop('shares')
67         e.amount = Decimal(self.form_result.pop('amount') * 100)
68         update_sar(e, self.form_result)
69         if e.id is not None:
70             e.update_split()
71
72         users = dict(meta.Session.query(model.User.id, model.User).all())
73         split_dict = {}
74         for share_params in shares:
75             user = users[share_params['user_id']]
76             split_dict[user] = Decimal(share_params['amount'])
77         e.split(split_dict)
78         
79         meta.Session.commit()
80         
81         h.flash('Expenditure updated.')
82        
83         return h.redirect_to('/')