devicehub-django/admin/views.py

237 lines
7.4 KiB
Python
Raw Normal View History

2024-12-11 20:18:46 +00:00
import logging
2024-10-14 15:02:40 +00:00
from smtplib import SMTPException
2024-12-01 22:47:40 +00:00
from django.contrib import messages
2024-10-07 14:56:24 +00:00
from django.urls import reverse_lazy
from django.shortcuts import get_object_or_404, redirect, Http404
2024-10-03 15:46:02 +00:00
from django.utils.translation import gettext_lazy as _
2024-12-02 19:55:59 +00:00
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.base import TemplateView, ContextMixin
2024-10-07 14:56:24 +00:00
from django.views.generic.edit import (
CreateView,
UpdateView,
DeleteView,
)
2024-12-01 22:47:40 +00:00
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
2024-10-11 15:15:37 +00:00
from dashboard.mixins import DashboardView, Http403
from admin.forms import OrderingStateForm
2024-10-11 15:04:33 +00:00
from user.models import User, Institution
2024-10-14 15:02:40 +00:00
from admin.email import NotifyActivateUserByEmail
2024-12-02 19:55:59 +00:00
from action.models import StateDefinition
2024-10-03 15:46:02 +00:00
2024-12-11 20:18:46 +00:00
device_logger = logging.getLogger('device_log')
2024-10-11 15:15:37 +00:00
class AdminView(DashboardView):
def get(self, *args, **kwargs):
response = super().get(*args, **kwargs)
if not self.request.user.is_admin:
raise Http403
return response
class PanelView(AdminView, TemplateView):
2024-10-03 15:46:02 +00:00
template_name = "admin_panel.html"
title = _("Admin")
breadcrumb = _("admin") + " /"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
2024-10-11 15:15:37 +00:00
class UsersView(AdminView, TemplateView):
2024-10-03 15:46:02 +00:00
template_name = "admin_users.html"
title = _("Users")
breadcrumb = _("admin / Users") + " /"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({
"users": User.objects.filter()
})
return context
2024-10-07 14:56:24 +00:00
2024-10-14 15:02:40 +00:00
class CreateUserView(AdminView, NotifyActivateUserByEmail, CreateView):
2024-10-07 14:56:24 +00:00
template_name = "user.html"
title = _("User")
breadcrumb = _("admin / User") + " /"
success_url = reverse_lazy('admin:users')
model = User
fields = (
"email",
"password",
"is_admin",
)
def form_valid(self, form):
form.instance.institution = self.request.user.institution
form.instance.set_password(form.instance.password)
response = super().form_valid(form)
2024-10-14 15:02:40 +00:00
try:
self.send_email(form.instance)
except SMTPException as e:
messages.error(self.request, e)
2024-10-07 14:56:24 +00:00
return response
2024-10-11 15:15:37 +00:00
class DeleteUserView(AdminView, DeleteView):
2024-10-07 14:56:24 +00:00
template_name = "delete_user.html"
title = _("Delete user")
breadcrumb = "admin / Delete user"
success_url = reverse_lazy('admin:users')
model = User
fields = (
"email",
"password",
"is_admin",
)
def form_valid(self, form):
response = super().form_valid(form)
return response
2024-10-11 15:15:37 +00:00
class EditUserView(AdminView, UpdateView):
2024-10-07 14:56:24 +00:00
template_name = "user.html"
title = _("Edit user")
breadcrumb = "admin / Edit user"
success_url = reverse_lazy('admin:users')
model = User
fields = (
"email",
"is_admin",
)
def get_form_kwargs(self):
pk = self.kwargs.get('pk')
self.object = get_object_or_404(self.model, pk=pk)
#self.object.set_password(self.object.password)
kwargs = super().get_form_kwargs()
return kwargs
2024-10-11 15:04:33 +00:00
2024-10-11 15:15:37 +00:00
class InstitutionView(AdminView, UpdateView):
2024-10-11 15:04:33 +00:00
template_name = "institution.html"
title = _("Edit institution")
section = "admin"
subtitle = _('Edit institution')
model = Institution
success_url = reverse_lazy('admin:panel')
fields = (
"name",
"logo",
"location",
"responsable_person",
"supervisor_person"
)
def get_form_kwargs(self):
self.object = self.request.user.institution
kwargs = super().get_form_kwargs()
return kwargs
2024-12-01 05:58:22 +00:00
2024-12-02 19:55:59 +00:00
class StateDefinitionContextMixin(ContextMixin):
2024-12-01 05:58:22 +00:00
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({
2024-12-02 19:55:59 +00:00
"state_definitions": StateDefinition.objects.filter(institution=self.request.user.institution).order_by('order'),
2024-12-01 05:58:22 +00:00
})
return context
2024-12-02 19:55:59 +00:00
2024-12-11 20:18:46 +00:00
2024-12-02 19:55:59 +00:00
class StatesPanelView(AdminView, StateDefinitionContextMixin, TemplateView):
template_name = "states_panel.html"
title = _("States")
breadcrumb = _("admin / States") + " /"
2024-12-11 20:18:46 +00:00
2024-12-02 19:55:59 +00:00
class AddStateDefinitionView(AdminView, StateDefinitionContextMixin, CreateView):
2024-12-01 22:47:40 +00:00
template_name = "states_panel.html"
title = _("New State Definition")
breadcrumb = "Admin / New state"
success_url = reverse_lazy('admin:states_panel')
2024-12-01 22:47:40 +00:00
model = StateDefinition
fields = ('state',)
def form_valid(self, form):
form.instance.institution = self.request.user.institution
form.instance.user = self.request.user
try:
response = super().form_valid(form)
2024-12-11 20:18:46 +00:00
messages.success(self.request, _("State definition successfully added."))
device_logger.info(f"<Created> StateDefinition with value {form.instance.state} by user {self.request.user}.")
2024-12-01 22:47:40 +00:00
return response
except IntegrityError:
2024-12-02 19:55:59 +00:00
messages.error(self.request, _("State is already defined."))
2024-12-01 22:47:40 +00:00
return self.form_invalid(form)
2024-12-02 19:55:59 +00:00
def form_invalid(self, form):
return super().form_invalid(form)
class DeleteStateDefinitionView(AdminView, StateDefinitionContextMixin, SuccessMessageMixin, DeleteView):
model = StateDefinition
success_url = reverse_lazy('admin:states_panel')
2024-12-02 19:55:59 +00:00
def get_success_message(self, cleaned_data):
2024-12-11 20:18:46 +00:00
device_logger.info(f"<Deleted> StateDefinition with value {self.object.state} by user {self.request.user}.")
2024-12-02 19:55:59 +00:00
return f'State definition: {self.object.state}, has been deleted'
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
#only an admin of current institution can delete
if not object.institution == self.request.user.institution:
raise Http404
return super().delete(request, *args, **kwargs)
2024-12-11 20:18:46 +00:00
class UpdateStateOrderView(AdminView, TemplateView):
success_url = reverse_lazy('admin:states_panel')
def post(self, request, *args, **kwargs):
form = OrderingStateForm(request.POST)
if form.is_valid():
ordered_ids = form.cleaned_data["ordering"].split(',')
with transaction.atomic():
current_order = 1
2024-12-11 20:18:46 +00:00
_log = []
for lookup_id in ordered_ids:
state_definition = StateDefinition.objects.get(id=lookup_id)
state_definition.order = current_order
state_definition.save()
2024-12-11 20:18:46 +00:00
_log.append(f"{state_definition.state} (ID: {lookup_id} -> Order: {current_order})")
current_order += 1
2024-12-11 20:18:46 +00:00
device_logger.info(
f"<Updated Order> State order updated by user {self.request.user}: {', '.join(_log)}"
)
messages.success(self.request, _("Order changed succesfuly."))
return redirect(self.success_url)
else:
return Http404
class UpdateStateDefinitionView(AdminView, UpdateView):
model = StateDefinition
template_name = 'states_panel.html'
fields = ['state']
pk_url_kwarg = 'pk'
def get_queryset(self):
return StateDefinition.objects.filter(institution=self.request.user.institution)
def get_success_url(self):
messages.success(self.request, _("State definition updated successfully."))
return reverse_lazy('admin:states_panel')
def form_valid(self, form):
return super().form_valid(form)