Skip to content

Commit

Permalink
create admin site with finance summary and graph
Browse files Browse the repository at this point in the history
  • Loading branch information
marosmola committed Oct 28, 2020
1 parent 7f16ba1 commit db87a1f
Show file tree
Hide file tree
Showing 4 changed files with 160 additions and 4 deletions.
62 changes: 60 additions & 2 deletions teachers/admin.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import json

from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models import Avg, Sum
from django.db.models.functions import Trunc

from .models import Teacher, TeacherSalary
from .models import Teacher, TeacherSalary, FinanceSummary
from easyschool.utils import ExportCsvMixin

from students.models import StudentFee

# Change User Creation Form
class UserCreationFormExtended(UserCreationForm):
Expand Down Expand Up @@ -95,3 +99,57 @@ def get_actions(self, request):
actions = [
'export_as_csv',
]

@admin.register(FinanceSummary)
class FinanceSummaryAdmin(admin.ModelAdmin):
change_list_template = 'admin/sale_summary_change_list.html'

def changelist_view(self, request, extra_context=None):
response = super().changelist_view(
request,
extra_context=extra_context,
)

monthly_salaries = TeacherSalary.objects.annotate(
month=Trunc('paid_on', 'month')).values('month').annotate(total=Sum('total_amount'))
monthly_fees = StudentFee.objects.annotate(
month=Trunc('date_submitted', 'month')).values('month').annotate(total=Sum('total_amount'))

data = {}
for salary in monthly_salaries:
month_year = "{}-{}".format(salary['month'].month, salary['month'].year)
data[month_year] = {
"salaries": salary['total'],
"fees": 0
}

for fee in monthly_fees:
month_year = "{}-{}".format(fee['month'].month, fee['month'].year)
data[month_year]['fees'] = fee['total']


# Prepare data to graph format
labels, salaries, fees = ([] for i in range(3))
for key, value in data.items():
labels.append(key)
salaries.append(value['salaries'])
fees.append(value['fees'])


# Scructure of graph_data is defined by Graph.js
graph_data = {
'labels': labels,
'datasets': [{
'label': "Teacher",
'backgroundColor': "blue",
'data': salaries
}, {
'label': "Student",
'backgroundColor': "red",
'data': fees
}]
}

response.context_data['data'] = data
response.context_data['graph_data'] = json.dumps(graph_data)
return response
25 changes: 25 additions & 0 deletions teachers/migrations/0002_teachersalary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 3.1.2 on 2020-10-27 12:34

import datetime
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('teachers', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='TeacherSalary',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('valid_until', models.DateField(default=datetime.date(2020, 11, 1), verbose_name='Valid Until')),
('total_amount', models.PositiveIntegerField(default=0)),
('paid_on', models.DateTimeField(auto_now_add=True)),
('teacher', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='teachers.teacher')),
],
),
]
11 changes: 9 additions & 2 deletions teachers/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,15 @@ class TeacherSalary(models.Model):
paid_on = models.DateTimeField(auto_now_add=True)

def __str__(self):
return f'Fee : {self.student.full_name()} {str(self.date_submitted)}'
return f'Salary : {self.teacher.full_name} {str(self.paid_on)}'

@property
def month_name(self):
return calendar.month_name[valid_until.month]
return calendar.month_name[valid_until.month]


class FinanceSummary(TeacherSalary):
class Meta:
proxy = True
verbose_name = 'Finance Summary'
verbose_name_plural = 'Finance Summary'
66 changes: 66 additions & 0 deletions teachers/templates/admin/sale_summary_change_list.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{% extends 'admin/change_list.html' %}
{% block content_title %}
<h1>Finance Summary </h1>
{% endblock %}

{% load humanize %}
{% block result_list %}

<canvas id="myChart" width="400" height="400"></canvas>
<div class=”results”>
<table>
<thead>
<tr>
<th>
<div class=”text”>
Month
</div>
</th>
<th>
<div class=”text”>
Salaries
</div>
</th>
<th>
<div class=”text”>
Fees
</div>
</th>
</tr>
</thead>
<tbody>
{% for key, value in data.items %}
<tr class="{% cycle 'row1' 'row2' %}">
<td> {{ key }} </td>
<td> {{ value.salaries }} </td>
<td> {{ value.fees }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script type="text/javascript">
var ctx = document.getElementById("myChart").getContext("2d");
var data = JSON.parse("{{ graph_data | escapejs }}")

var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
responsive: false,
barValueSpacing: 20,
scales: {
yAxes: [{
ticks: {
min: 0,
}
}]
}
}
});

</script>
{% endblock %}
{% block pagination %}{% endblock %}

0 comments on commit db87a1f

Please sign in to comment.