1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
from flask import Blueprint
from flask import render_template, request, url_for, redirect
import datetime, decimal
from sqlalchemy import sql, func
from ..model import db, Category, SingleExpense, CatExpense, MonthExpense
from ..forms import ExpenseForm
mod = Blueprint('expenses', __name__)
def is_last(exp):
return exp.date >= datetime.date.today().replace(day = 1)
def calc_month_exp(year, month):
ssum = func.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(year, month, 1), exps)
def prev_date(exp):
if exp.date.month == 1:
return { "year": exp.date.year - 1, "month": 12 }
else:
return { "year": exp.date.year, "month": exp.date.month - 1 }
def next_date(exps):
def _next_date(exp):
if exp.date.month == 13 - len(exps):
return { "year": exp.date.year + 1, "month": 1 }
else:
return { "year": exp.date.year, "month": exp.date.month + len(exps) }
return _next_date
@mod.app_template_filter("date")
def format_date(s):
if hasattr(s, "date"):
return "%s/%s" % (s.date.year, s.date.month)
else:
return "%(year)s/%(month)s" % s
def render_show(exps, is_last):
return render_template("pages/show.jinja",
exps = exps, is_last = is_last,
prev_date = prev_date,
next_date = next_date(exps))
@mod.route("/<int(fixed_digits=4):year>/<int(fixed_digits=2):month>")
def show_date(year, month):
c = calc_month_exp(year, month)
return render_show([c], is_last(c))
@mod.route("/")
def show(year = None, month = None):
d = datetime.date.today()
first = calc_month_exp(d.year, d.month)
if d.month == 1:
second = calc_month_exp(d.year - 1, 12)
else:
second = calc_month_exp(d.year, d.month - 1)
return render_show([first, second], is_last(first))
@mod.route("/edit/<int:id>")
def edit(id):
return render_template("page.jinja")
@mod.route("/add/", methods=("GET", "POST"))
def add():
form = ExpenseForm()
form.category.query = Category.query.order_by("name")
if form.validate_on_submit():
se = SingleExpense()
form.populate_obj(se)
db.session.add(se)
db.session.commit()
return redirect(url_for("index"))
return render_template("pages/add.jinja", form=form)
|