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("//") 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/") 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)