Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added page with information for regular users #45

Merged
merged 5 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions admin_board_view/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from functools import wraps
from django.http.response import HttpResponseRedirect

# Decorator to check if a user is authenticated
def dashboard_authenticated(f):
"""
Check if the user is logged in, if not redirect to login page
"""
@wraps(f)
def decorator(*args, **kwargs):
request = args[0]
if not request.user.is_authenticated:
return HttpResponseRedirect("/login")

return f(*args, **kwargs)
return decorator


def dashboard_admin(f):
"""
Check if the user is logged in and is an admin, if not redirect to login page
"""
@wraps(f)
def decorator(*args, **kwargs):
request = args[0]
if not request.user.is_superuser:
return HttpResponseRedirect("/login")

return f(*args, **kwargs)
return decorator
27 changes: 5 additions & 22 deletions admin_board_view/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@
</div>
</nav>
<div class="d-flex" style="min-height: calc(100vh - 56px);">
{% if user.is_superuser %}
<div class="d-flex flex-column flex-shrink-0 p-3 text-white bg-dark" style="width: 280px;">
<div class="nav nav-pills flex-column mb-auto">
<a href="/" class="nav-link text-white" aria-current="page">
Home
</a>
{% if user.is_superuser %}
<a href="/products" class="nav-link text-white">
Products
</a>
Expand All @@ -54,18 +54,22 @@
<a href="/transactions" class="nav-link text-white">
Transactions
</a>
{% endif %}
</div>
<hr>
{% if user.is_authenticated %}
<div class="dropdown">
<a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false">
<strong>{{ user.email }}</strong>
</a>
<ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdownUser1">
<form action="{% url 'oidc_logout' %}" method="post">
{% csrf_token %}
<input class="dropdown-item" type="submit" value="Sign out">
</form>
</ul>
</div>
{% endif %}
</div>
<main class="container d-flex flex-column mt-3" style="width: calc(100% - 300px);">
{% block body %}
Expand Down Expand Up @@ -95,27 +99,6 @@ <h5 class="modal-title" id="confirm-title"></h5>
</div>
</div>
</main>
{% elif user.is_authenticated %}
<main class="container mt-3">
<h1>Not allowed</h1>
<p>
You are not allowed to view this page as a non admin. Please logout and try again:
</p>
<form action="{% url 'oidc_logout' %}" method="post">
{% csrf_token %}
<button class="btn btn-primary" type="submit">Logout</button>
</form>

</main>
{% else %}
<main class="container mt-3">
<h1>Unauthenticated</h1>
<p>
You are currently not logged in. Please log in using an admin account:
</p>
<a href="{% url 'oidc_authentication_init' %}"><button class="btn btn-primary">Login</button></a>
</main>
{% endif %}
</div>
</body>
</html>
11 changes: 11 additions & 0 deletions admin_board_view/templates/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{% extends "base.html" %}
{% load static %}
{% block body %}
<main class="container mt-3">
<h1>Unauthenticated</h1>
<p>
You are currently not logged in. Please log in using a koala account:
</p>
<a href="{% url 'oidc_authentication_init' %}"><button class="btn btn-primary">Login</button></a>
</main>
{% endblock %}
69 changes: 69 additions & 0 deletions admin_board_view/templates/user_home.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{% extends "base.html" %}
{% load static %}
{% block body %}
<main class="container mt-3">
<h1>Welcome {{ user_info.name }}</h1>
<h5 class="mb-2">
Current balance: <b>{{ user_info.euro_balance }}</b>
</h5>
<hr/>
<div class="row row-cols-2">
<div class="col">
<div class="card">
<h5 class="card-header">Product sales</h5>
<div class="card-body">
<table class="table table-striped table-hover text-center align-middle">
<thead>
<tr>
<th>Date</th>
<th>Sum</th>
<th>Products</th>
</tr>
</thead>
<tbody>
{% for transaction in sales %}
<tr id="{{ transaction.key.id }}">
<td>{{ transaction.key.date }}</td>
<td>€{{ transaction.key.transaction_sum }}</td>
<td>
{% for product in transaction.values %}
{{ product.amount }}x {{ product.product_id.name }}<br/>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% include "pagination_footer.html" with page=sales page_name='sales' %}
</div>
</div>
</div>
<div class="col">
<div class="card">
<h5 class="card-header">Top ups</h5>
<div class="card-body">
<table class="table table-striped table-hover text-center align-middle">
<thead>
<tr>
<th>Date</th>
<th>Sum</th>
<th>Type</th>
</tr>
</thead>
<tbody>
{% for top_up in top_ups.object_list %}
<tr>
<td>{{ top_up.date }}</td>
<td>€{{ top_up.transaction_sum }}</td>
<td>{% if top_up.type == 1 %}Pin{% elif top_up.type == 3 %}Mollie{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% include "pagination_footer.html" with page=top_ups page_name='top_ups' %}
</div>
</div>
</div>
</div>
</main>
{% endblock %}
2 changes: 2 additions & 0 deletions admin_board_view/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

urlpatterns = [
path('', views.index, name='index'),
path('login', views.login, name='login'),

path('products', views.products, name='products'),
path('users', views.users, name='users'),
path('users/<str:user_id>', views.users, name='user'),
Expand Down
19 changes: 19 additions & 0 deletions admin_board_view/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from django.core.paginator import Paginator

def create_paginator(data, page, p_len=5):
"""
Create paginator for data.

Args:
data: Data to paginate
page: Page number
p_len: Length of the page, defaults to 5
"""
page = None
paginator = Paginator(data, p_len)
try:
page = paginator.get_page(page)
except Exception:
page = paginator.page(1)

return page
82 changes: 45 additions & 37 deletions admin_board_view/views.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,44 @@
import json

from django.db.models import Sum
from django.core.paginator import Paginator
from django.http.response import JsonResponse
from django.shortcuts import render, HttpResponseRedirect
from django.http import HttpResponse
from django.utils import timezone
from itertools import groupby

from admin_board_view.middleware import dashboard_authenticated, dashboard_admin
from admin_board_view.utils import create_paginator
from .models import *
import json


@dashboard_authenticated
def index(request):
product_amount = Product.objects.count()
total_balance = sum(user.balance for user in User.objects.all())
return render(request, "home.html", {"users": User.objects.all(), "product_amount": product_amount, "total_balance": total_balance, "top_types": top_up_types })
if request.user.is_superuser:
product_amount = Product.objects.count()
total_balance = sum(user.balance for user in User.objects.all())
return render(request, "home.html", {"users": User.objects.all(), "product_amount": product_amount, "total_balance": total_balance, "top_types": top_up_types })
else:
user = User.objects.get(user_id=request.user.id)

# Get product sales
product_sales = list(ProductTransactions.objects.all().filter(transaction_id__user_id=user))
product_sale_groups = []
for designation, member_group in groupby(product_sales, lambda sale: sale.transaction_id):
product_sale_groups.append({ "key": designation, "values": list(member_group) })
sales_page = create_paginator(product_sale_groups, request.GET.get('sales'))

# Get topup page
top_ups = TopUpTransaction.objects.all().filter(user_id=user)
top_up_page = create_paginator(top_ups, request.GET.get('top_ups'))
return render(request, "user_home.html", {"user_info": user, "top_ups": top_up_page, "sales": sales_page })


def login(request):
return render(request, "login.html")


@dashboard_admin
def products(request):
if request.POST:
product = ProductForm(request.POST, request.FILES)
Expand Down Expand Up @@ -47,12 +71,14 @@ def products(request):
return render(request, "products.html", { "products": products, "categories": categories, "product_form": pf, "current_product": product, "product_sales": product_sales })


@dashboard_admin
def delete(request):
id = request.POST.dict()['id']
Product.objects.get(id=id).delete()
return JsonResponse({ "msg": f"Deleted product with {id}" })


@dashboard_admin
def toggle(request):
id = request.POST.dict()['id']
product = Product.objects.get(id=id)
Expand All @@ -61,6 +87,7 @@ def toggle(request):
return JsonResponse({ "msg": f"Set the state of product {id} to enabled={product.enabled}" })


@dashboard_admin
def users(request, user_id=None):
user, cards = None, None
if user_id:
Expand All @@ -77,33 +104,24 @@ def users(request, user_id=None):
if card.active is False:
cards[i]["token"] = CardConfirmation.objects.get(card=card).token

top_up_page = None
top_ups_paginator = Paginator(top_ups, 5)
try:
top_up_page = top_ups_paginator.get_page(request.GET.get('top_ups'))
except Exception:
top_up_page = top_ups_paginator.page(1)

sales_page = None
sales_paginator = Paginator(product_sale_groups, 5)
try:
sales_page = sales_paginator.get_page(request.GET.get('sales'))
except Exception:
sales_page = sales_paginator.page(1)
top_up_page = create_paginator(top_ups, request.GET.get('top_ups'))
sales_page = create_paginator(product_sale_groups, request.GET.get('sales'))

return render(request, "user.html", { "user_info": user, "cards": cards, "top_ups": top_up_page, "sales": sales_page, "top_types": top_up_types })
else:
users = User.objects.all()
return render(request, "user.html", { "users": users })


@dashboard_admin
def settings_page(request):
vat = VAT.objects.all()
categories = Category.objects.all()
configuration = Configuration.objects.get(pk=1)
return render(request, "settings.html", { "vat": vat, "categories": categories, "configuration": configuration })


@dashboard_admin
def category(request):
try:
categories = json.loads(request.POST.dict()['categories'])
Expand All @@ -126,6 +144,7 @@ def category(request):
return JsonResponse({ "msg": "Something went wrong whilst trying to save the categories" }, status=400)


@dashboard_admin
def vat(request):
try:
vatBody = json.loads(request.POST.dict()['vat'])
Expand All @@ -147,6 +166,7 @@ def vat(request):
return JsonResponse({ "msg": "Something went wrong whilst trying to save the VAT percentages" }, status=400)


@dashboard_admin
def settings_update(request):
"""
Updates the configuration settings for the undead-mongoose application.
Expand All @@ -168,31 +188,23 @@ def settings_update(request):
return JsonResponse({ "msg": "Something went wrong whilst trying to save the configuration" }, status=400)


@dashboard_admin
def transactions(request):
# Top up paginator
top_ups = TopUpTransaction.objects.all()
top_ups_paginator = Paginator(top_ups, 5)
try:
top_up_page = top_ups_paginator.get_page(request.GET.get('top_ups'))
except Exception:
top_up_page = top_ups_paginator.page(1)

# Product sale paginator
# Get product sale groups
product_sales = ProductTransactions.objects.all()
product_sales_sorted = sorted(product_sales, key=lambda sale: sale.transaction_id.date, reverse=True)
product_sale_groups = []
for designation, member_group in groupby(product_sales_sorted, lambda sale: sale.transaction_id):
product_sale_groups.append({ "key": designation, "values": list(member_group) })

sales_paginator = Paginator(product_sale_groups, 10)
try:
sales_page = sales_paginator.get_page(request.GET.get('sales'))
except Exception:
sales_page = sales_paginator.page(1)

# Get paginators
top_up_page = create_paginator(TopUpTransaction.objects.all(), request.GET.get('top_ups'))
sales_paginator = create_paginator(product_sale_groups, request.GET.get('sales'), p_len=10)

return render(request, "transactions.html", { "top_ups": top_up_page, "sales": sales_page })


@dashboard_admin
def export_sale_transactions(request):
"""
Exports the sale transactions in the given date range to a csv file.
Expand All @@ -203,10 +215,6 @@ def export_sale_transactions(request):
Returns:
HttpResponse: The csv file containing the sale transactions in the given date range.
"""
# Only allow export for authanticated users
if not request.user.is_superuser:
return HttpResponse("You are not authenticated.", status=401)

try:
req_get = request.GET
export_type = req_get.get('type')
Expand Down
Loading