from __future__ import with_statement import web from web import form from model import * from helper import appdir from renderer import render import datetime, decimal import operator as op from sqlalchemy import sql class Show: def GET(self, year = '', month = ''): if year: return self.render([self.calc(year, month)]) else: d = datetime.date.today() first = self.calc(d.year, d.month) if d.month == 1: second = self.calc(d.year - 1, 12) else: second = self.calc(d.year, d.month - 1) return self.render([first, second]) def calc(self, year, month): year = int(year) month = int(month) ssum = sql.functions.sum(SingleExpense.expense) query = SingleExpense.of_month(month, year) result = query.group_by(SingleExpense.category_id).\ values(SingleExpense.category_id, ssum) exps = [CatExpense(Category.query.get(c), s, query.filter(SingleExpense.category_id == c)) for c,s in result] return MonthExpense(datetime.date(int(year), int(month), 1), exps) def render(self, exps): return render("show", exps = exps) class Add: dformat = "%d.%m.%Y" def GET(self): return render("add", form = self.form()) def POST(self): f = self.form() if f.validates(): e = SingleExpense(category = Category.get_by(name = f.category.value)) e.date = datetime.datetime.strptime(f.date.value, self.dformat) e.expense = decimal.Decimal(f.expense.value) e.description = f.description.value raise web.seeother("/") else: return render("add", form = f) @property def form(self): return form.Form( form.Textbox( "date", form.notnull, value = datetime.date.today().strftime(self.dformat) ), form.Textbox( "expense", form.notnull, ), form.Textbox( "description", form.notnull ), form.Dropdown( "category", map(op.itemgetter(0), sorted(Category.query.values(Category.name))) ), validators = map(lambda x: form.Validator(*x), ( ("Date Format does not match", lambda f: datetime.datetime.strptime(f.date, self.dformat)), ("Not a valid decimal", lambda f: decimal.Decimal(f.expense)), )) ) class Edit: def GET(self, id): return "Edit " + id class Const: def GET(self): return "Const" class ConstAdd: def GET(self): return "Add new const" class ConstEdit: def GET(self, id): return "Const Edit " + id class Cat: def GET(self, id = '/'): if id: id = id[1:] if not id: return "Add new cat" else: return "Edit cat " + id class FourOhFour: """ 404 error page. """ def GET (self, p): raise self.catch(p) @staticmethod def catch (page = "?"): return web.notfound(render("404", page = page))