schmeckels/report.py
2020-05-23 13:55:21 +02:00

64 lines
1.8 KiB
Python

#! /usr/bin/env python3
from models import Category, Transaction
from helper import get_session
import sys
import click
from bottle import template
from sqlalchemy import func
from weasyprint import HTML
from datetime import date
from helper import format_amount
@click.command(name="report")
@click.option("--profile", "-p")
@click.option("--year", "-y")
def command(profile, year):
if not year:
year = date.today().year
session = get_session(profile)
result = (
session.query(
Transaction.category_id,
Category.name,
func.sum(Transaction.amount).label("total"),
)
.group_by(Transaction.category_id)
.join(Category, Transaction.category_id == Category.id)
.all()
)
sum_of_categories = []
for r in result:
tmp = {}
tmp["name"] = r.name
tmp["total"] = r.total
tmp["total_formatted"] = format_amount(r.total)
tmp["full_name"] = session.query(Category).get(r.category_id).full_name()
sum_of_categories.append(tmp)
categories = sorted(sum_of_categories, key=lambda i: i["name"])
einnahmen = [c for c in categories if c["total"] > 0]
ausgaben = [c for c in categories if c["total"] < 0]
sum_einnahmen = sum(c["total"] for c in einnahmen)
sum_ausgaben = sum(c["total"] for c in ausgaben)
total = {
"einnahmen": format_amount(sum_einnahmen),
"ausgaben": format_amount(sum_ausgaben),
"total": format_amount(sum_einnahmen + sum_ausgaben),
}
context = {
"einnahmen": einnahmen,
"ausgaben": ausgaben,
"year": year,
"total": total,
}
tpl = template("views/report.tpl", context)
filename = "output/report_{}_{}.pdf".format(profile, year)
HTML(string=tpl).write_pdf(filename)
print("Report saved to {}".format(filename))