from . import Blueprint, db, \ current_user, login_required, \ assert_authorisation, templated, redirect, request from ..model import Category, ConstExpense from ..forms import ConstForm, today import datetime from sqlalchemy import sql from functools import partial assert_authorisation = partial(assert_authorisation, ConstExpense.get) mod = Blueprint('consts', __name__) def const_form(cur=None, obj=None): obj = cur if obj is None else obj form = ConstForm(obj=obj) form.category.query = Category.of(current_user).order_by(Category.name) # init prev_list CE = ConstExpense filter = (CE.next == None) if cur and cur.id is not None: # not empty filter = sql.or_(CE.next == cur, filter) filter = sql.and_(filter, CE.id != cur.id) form.prev.query = CE.of(current_user).filter(filter).order_by(CE.description) return form @mod.route('/') @login_required @templated() def list (): d = today() expenses = ConstExpense.of(current_user).order_by(ConstExpense.description).all() current = [] old = [] future = [] for e in expenses: if e.start <= d: if e.end >= d: current.append(e) else: old.append(e) else: future.append(e) return { 'current': current, 'old': old, 'future': future } @mod.route('/') @login_required @assert_authorisation('id') @templated() def show(id): return { 'exp': ConstExpense.get(id) } @mod.route('/edit/', methods=('GET', 'POST')) @login_required @assert_authorisation('id') @templated() def edit(id): exp = ConstExpense.get(id) form = const_form(exp) if form.is_submitted(): if 'deleteB' in request.form: db.session.delete(exp) db.session.commit() return redirect('.list') elif form.validate(): # change form.populate_obj(exp) db.session.commit() return redirect('.show', id = id) return { 'form': form } @mod.route('/add/from/') @login_required @assert_authorisation('other') @templated('.add') def add_from(other): exp = ConstExpense() # needed to initialize 'CE.next' other = ConstExpense.get(other) # get form with data from other form = const_form(obj = other) # replace some fields to be more meaningful start = max(form.end.data, today()) form.start.data = start form.end.data = start.replace(year = start.year + 1) if not other.next: form.prev.data = other return { 'form': form } @mod.route('/add/', methods=('GET', 'POST')) @login_required @templated() def add (): exp = ConstExpense() form = const_form() if form.validate_on_submit(): form.populate_obj(exp) exp.user = current_user db.session.add(exp) db.session.commit() return redirect('.show', id = exp.id) return { 'form': form }