summaryrefslogtreecommitdiff
path: root/app/views/expenses.py
blob: 870b45f109250eb123f15077508e14f8b0b5306d (plain)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# -*- coding: utf-8 -*-
from . import Blueprint, flash, db, \
        current_user, login_required, \
        assert_authorisation, templated, redirect, request, url_for, today

from flask import Markup

from ..model import Category, SingleExpense, CatExpense, MonthExpense
from .. import forms as F

import datetime
from sqlalchemy import sql, func
from functools import partial

assert_authorisation = partial(assert_authorisation, SingleExpense.get)
mod = Blueprint('expenses', __name__)

class ExpenseForm(F.Form):
    date = F.DateField(u'Datum', F.req,
            format="%d.%m.%Y",
            default=lambda: today())

    expense = F.DecimalField(u'Betrag', F.req,
            description=u'EUR',
            places=2)

    description = F.StringField(u'Beschreibung', F.req)

    category = F.QuerySelectField(u'Kategorie',
            get_label='name')

    def __init__(self, obj = None):
        super(F.Form, self).__init__(obj = obj)
        self.category.query = Category.of(current_user).order_by(Category.name)

def calc_month_exp(year, month):
    ssum = func.sum(SingleExpense.expense)
    query = SingleExpense.of_month(current_user, 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(current_user, datetime.date(year, month, 1), exps)

def pie_stuff(exp):
    expenses = {}
    for c in exp.catexps:
        expenses[c.cat.name] = float(c.expense)

    for c in Category.of(current_user).order_by(Category.name).all():
        yield (c.name, expenses.get(c.name, 0.0))

def calc_month_and_pie(year, month):
    exp = calc_month_exp(year,month)
    pie = pie_stuff(exp)
    return (exp, dict(pie))

def entry_flash(msg, exp):
    url = url_for('.edit', id = exp.id)
    link = u"<a href=\"%s\">%s</a>" % (url, exp.description)
    flash(Markup(msg % link))

@mod.app_template_filter()
def prev_date(exp):
    if exp.date.month == 1:
        return exp.date.replace(year = exp.date.year - 1, month = 12)
    else:
        return exp.date.replace(month = exp.date.month - 1)

@mod.app_template_filter()
def next_date(exp):
    if exp.date.month == 12:
        return exp.date.replace(year = exp.date.year + 1, month = 1)
    else:
        return exp.date.replace(month = exp.date.month + 1)

@mod.app_template_test('last_date')
def is_last(exp):
    return exp.date >= today().replace(day = 1)

@mod.route('/<int(fixed_digits=4):year>/<int(fixed_digits=2):month>')
@login_required
@templated('.show')
def show_date(year, month):
    c,p = calc_month_and_pie(year, month)
    return { 'exps' : [c], 'pies' : [p] }

mod.add_url_rule('/<path:p>', endpoint = 'show_date_str', build_only = True)

@mod.route('/')
@login_required
@templated
def show():
    d = today()
            
    first, pfirst = calc_month_and_pie(d.year, d.month)
    if d.month == 1:
        second, psecond = calc_month_and_pie(d.year - 1, 12)
    else:
        second, psecond = calc_month_and_pie(d.year, d.month - 1)

    return { 'exps' : [first, second], 'pies': [pfirst, psecond] }

@mod.route('/edit/<int:id>', methods=('GET', 'POST'))
@login_required
@assert_authorisation('id')
@templated
def edit(id):
    exp = SingleExpense.get(id)
    form = ExpenseForm(exp)

    if form.is_submitted():
        if 'deleteB' in request.form:
            db.session.delete(exp)

        elif form.flash_validate(): # change
            form.populate_obj(exp)

        else:
            return { 'form': form }

        db.session.commit()
        entry_flash(u"Eintrag %s geändert.", exp)
        return redirect('index')

    return { 'form': form }

@mod.route('/add/', methods=('GET', 'POST'))
@login_required
@templated
def add():
    form = ExpenseForm()

    if form.validate_on_submit():
        exp = SingleExpense()

        form.populate_obj(exp)
        exp.user = current_user

        db.session.add(exp)
        db.session.commit()

        entry_flash(u"Neuer Eintrag %s hinzugefügt.", exp)

        return redirect('.add')

    return { 'form': form }