Add timeline per category

This commit is contained in:
Edgar P. Burkhart 2022-12-20 16:14:06 +01:00
parent d88ba21869
commit bbcaf1c1d3
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227
2 changed files with 34 additions and 0 deletions

View file

@ -5,4 +5,5 @@ from . import views
urlpatterns = [ urlpatterns = [
path("timeline", views.timeline, name="timeline"), path("timeline", views.timeline, name="timeline"),
path("categories", views.categories, name="categories"), path("categories", views.categories, name="categories"),
path("category/<uuid>", views.category, name="category"),
] ]

View file

@ -5,6 +5,7 @@ import matplotlib.pyplot as plt
from matplotlib import dates as mdates from matplotlib import dates as mdates
from django.db import models from django.db import models
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponse from django.http import HttpResponse
from django.utils.translation import gettext as _ from django.utils.translation import gettext as _
@ -63,3 +64,35 @@ def categories(request):
fig.savefig(_io, format="svg") fig.savefig(_io, format="svg")
return HttpResponse(_io.getvalue(), headers={"Content-Type": "image/svg+xml"}) return HttpResponse(_io.getvalue(), headers={"Content-Type": "image/svg+xml"})
@login_required
def category(request, uuid):
_category = get_object_or_404(Category, id=uuid)
_values = (
Transaction.objects.filter(category=_category)
.annotate(m=models.functions.TruncMonth("date"))
.values("m")
.annotate(sum=models.Sum("value"))
.order_by("m")
)
fig, ax = plt.subplots()
ax.step(
[v["m"] for v in _values],
[v["sum"] for v in _values],
where="post",
)
ax.xaxis.set_major_formatter(
mdates.ConciseDateFormatter(ax.xaxis.get_major_locator())
)
ax.autoscale(True, "x", True)
_ym, _yp = ax.get_ylim()
ax.set(ylim=(min(_ym, 0), max(_yp, 0)))
ax.set(ylabel=f"{_category.name} (€)")
_io = io.StringIO()
fig.savefig(_io, format="svg")
return HttpResponse(_io.getvalue(), headers={"Content-Type": "image/svg+xml"})