Add snapshot plot

This commit is contained in:
Edgar P. Burkhart 2022-05-24 15:28:52 +02:00
parent 14fa4b38d0
commit b1b3a5afa2
Signed by: edpibu
GPG key ID: 9833D3C5A25BD227
3 changed files with 48 additions and 0 deletions

View file

@ -31,6 +31,9 @@
</div> </div>
</form> </form>
<h2>Plot</h2>
<img src="{% url 'snapshot_graph' snapshot.id %}" />
{% if snapshot.transactions %} {% if snapshot.transactions %}
<h2>Transactions ({% pmvalue sum %} / {% pmvalue snapshot.diff %})</h2> <h2>Transactions ({% pmvalue sum %} / {% pmvalue snapshot.diff %})</h2>

View file

@ -17,5 +17,6 @@ urlpatterns = [
path("category/<uuid>/del", views.del_category, name="del_category"), path("category/<uuid>/del", views.del_category, name="del_category"),
path("snapshot", views.snapshot, name="snapshot"), path("snapshot", views.snapshot, name="snapshot"),
path("snapshot/<uuid>", views.snapshot, name="snapshot"), path("snapshot/<uuid>", views.snapshot, name="snapshot"),
path("snapshot/<uuid>/graph.svg", views.snapshot_graph, name="snapshot_graph"),
path("snapshot/<uuid>/del", views.del_snapshot, name="del_snapshot"), path("snapshot/<uuid>/del", views.del_snapshot, name="del_snapshot"),
] ]

View file

@ -5,6 +5,9 @@ from django.contrib.auth import views as auth_views
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView from django.views.generic import ListView
from django.core.paginator import Paginator from django.core.paginator import Paginator
from django.db import models
import matplotlib.pyplot as plt
import tempfile
from .models import ( from .models import (
Transaction, Transaction,
@ -169,6 +172,47 @@ def snapshot(request, uuid=None):
) )
@login_required
def snapshot_graph(request, uuid):
_snapshot = get_object_or_404(Snapshot, id=uuid)
_categories_p = (
_snapshot.transactions.filter(value__gt=0)
.values("category")
.annotate(sum=models.Sum("value"))
)
_categories_m = (
_snapshot.transactions.filter(value__lt=0)
.values("category")
.annotate(sum=models.Sum("value"))
)
print(_categories_p)
print(_categories_m)
fig, ax = plt.subplots()
ax.bar(
[
"*" if (c := _cat["category"]) is None else Category.objects.get(id=c).name
for _cat in _categories_p
],
[_cat["sum"] for _cat in _categories_p],
color="#007339",
)
ax.bar(
[
"*" if (c := _cat["category"]) is None else Category.objects.get(id=c).name
for _cat in _categories_m
],
[_cat["sum"] for _cat in _categories_m],
color="#bf1500",
)
ax.grid(color="k", alpha=0.2)
ax.set(ylabel="Value (€)")
with tempfile.NamedTemporaryFile(suffix=".svg") as f:
fig.savefig(f.name)
f.seek(0)
return HttpResponse(f.read(), content_type="image/svg+xml")
@login_required @login_required
def del_snapshot(request, uuid): def del_snapshot(request, uuid):
_snapshot = get_object_or_404(Snapshot, id=uuid) _snapshot = get_object_or_404(Snapshot, id=uuid)