Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • konstantin/akplanning
  • matedealer/akplanning
  • kif/akplanning
  • mirco/akplanning
  • lordofthevoid/akplanning
  • voidptr/akplanning
  • xayomer/akplanning-fork
  • mollux/akplanning
  • neumantm/akplanning
  • mmarx/akplanning
  • nerf/akplanning
  • felix_bonn/akplanning
  • sebastian.uschmann/akplanning
13 results
Show changes
Showing
with 853 additions and 121 deletions
......@@ -13,36 +13,61 @@ from AKModel.models import Event
class EventSlugMixin:
"""
Mixin to handle views with event slugs
This will make the relevant event available as self.event in all kind types of requests
(generic GET and POST views, list views, dispatching, create views)
"""
# pylint: disable=no-member
event = None
def _load_event(self):
"""
Perform the real loading of the event data (as specified by event_slug in the URL) into self.event
"""
# Find event based on event slug
if self.event is None:
self.event = get_object_or_404(Event, slug=self.kwargs.get("event_slug", None))
def get(self, request, *args, **kwargs):
"""
Override GET request handling to perform loading event first
"""
self._load_event()
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
"""
Override POST request handling to perform loading event first
"""
self._load_event()
return super().post(request, *args, **kwargs)
def list(self, request, *args, **kwargs):
"""
Override list view request handling to perform loading event first
"""
self._load_event()
return super().list(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
"""
Override create view request handling to perform loading event first
"""
self._load_event()
return super().create(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs):
"""
Override dispatch which is called in many generic views to perform loading event first
"""
if self.event is None:
self._load_event()
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, *, object_list=None, **kwargs):
"""
Override `get_context_data` to make the event information available in the rendering context as `event`. too
"""
context = super().get_context_data(object_list=object_list, **kwargs)
# Add event to context (to make it accessible in templates)
context["event"] = self.event
......@@ -55,15 +80,29 @@ class FilterByEventSlugMixin(EventSlugMixin):
"""
def get_queryset(self):
# Filter current queryset based on url event slug or return 404 if event slug is invalid
"""
Get adapted queryset:
Filter current queryset based on url event slug or return 404 if event slug is invalid
:return: Queryset
"""
return super().get_queryset().filter(event=self.event)
class AdminViewMixin:
"""
Mixin to provide context information needed in custom admin views
Will either use default information for `site_url` and `title` or allows to set own values for that
"""
# pylint: disable=too-few-public-methods
site_url = ''
title = ''
def get_context_data(self, **kwargs):
"""
Extend context
"""
extra = admin.site.each_context(self.request)
extra.update(super().get_context_data(**kwargs))
......@@ -76,10 +115,19 @@ class AdminViewMixin:
class IntermediateAdminView(AdminViewMixin, FormView):
"""
Metaview: Handle typical "action but with preview and confirmation step before" workflow
"""
template_name = "admin/AKModel/action_intermediate.html"
form_class = AdminIntermediateForm
def get_preview(self):
"""
Render a preview of the action to be performed.
Default is empty
:return: preview (html)
:rtype: str
"""
return ""
def get_context_data(self, **kwargs):
......@@ -90,7 +138,18 @@ class IntermediateAdminView(AdminViewMixin, FormView):
class WizardViewMixin:
"""
Mixin to create wizard-like views.
This visualizes the progress of the user in the creation process and provides the interlinking to the next step
In the current implementation, the steps of the wizard are hardcoded here,
hence this mixin can only be used for the event creation wizard
"""
# pylint: disable=too-few-public-methods
def get_context_data(self, **kwargs):
"""
Extend context
"""
context = super().get_context_data(**kwargs)
context["wizard_step"] = self.wizard_step
context["wizard_steps"] = [
......@@ -107,10 +166,23 @@ class WizardViewMixin:
class IntermediateAdminActionView(IntermediateAdminView, ABC):
"""
Abstract base view: Intermediate action view (preview & confirmation see :class:`IntermediateAdminView`)
for custom admin actions (marking multiple objects in a django admin model instances list with a checkmark and then
choosing an action from the dropdown).
This will automatically handle the decoding of the URL encoding of the list of primary keys django does to select
which objects the action should be run on, then display a preview, perform the action after confirmation and
redirect again to the object list including display of a confirmation message
"""
# pylint: disable=no-member
form_class = AdminIntermediateActionForm
entities = None
def get_queryset(self, pks=None):
"""
Get the queryset of objects to perform the action on
"""
if pks is None:
pks = self.request.GET['pks']
return self.model.objects.filter(pk__in=pks.split(","))
......@@ -130,7 +202,10 @@ class IntermediateAdminActionView(IntermediateAdminView, ABC):
@abstractmethod
def action(self, form):
pass
"""
The real action to perform
:param form: form holding the data probably needed for the action
"""
def form_valid(self, form):
self.entities = self.get_queryset(pks=form.cleaned_data['pks'])
......@@ -140,7 +215,21 @@ class IntermediateAdminActionView(IntermediateAdminView, ABC):
class LoopActionMixin(ABC):
def action(self, form):
"""
Mixin for the typical kind of action where one needs to loop over all elements
and perform a certain function on each of them
The action is performed by overriding `perform_action(self, entity)`
further customization can be reached with the two callbacks `pre_action()` and `post_action()`
that are called before and after performing the action loop
"""
def action(self, form): # pylint: disable=unused-argument
"""
The real action to perform.
Will perform the loop, perform the action on each aelement and call the callbacks
:param form: form holding the data probably needed for the action
"""
self.pre_action()
for entity in self.entities:
self.perform_action(entity)
......@@ -149,10 +238,18 @@ class LoopActionMixin(ABC):
@abstractmethod
def perform_action(self, entity):
pass
"""
Action to perform on each entity
:param entity: entity to perform the action on
"""
def pre_action(self):
pass
"""
Callback for custom action before loop starts
"""
def post_action(self):
pass
"""
Callback for custom action after loop finished
"""
......@@ -8,6 +8,9 @@ from AKModel.metaviews.admin import AdminViewMixin
class StatusWidget(ABC):
"""
Abstract parent for status page widgets
"""
title = "Status Widget"
actions = []
status = "primary"
......@@ -18,7 +21,6 @@ class StatusWidget(ABC):
"""
Which model/context is needed to render this widget?
"""
pass
def get_context_data(self, context) -> dict:
"""
......@@ -32,6 +34,7 @@ class StatusWidget(ABC):
Render widget based on context
:param context: Context for rendering
:param request: HTTP request, needed for rendering
:return: Dictionary containing the rendered/prepared information
"""
context = self.get_context_data(context)
......@@ -42,7 +45,7 @@ class StatusWidget(ABC):
"status": self.render_status(context),
}
def render_title(self, context: {}) -> str:
def render_title(self, context: {}) -> str: # pylint: disable=unused-argument
"""
Render title for widget based on context
......@@ -52,7 +55,7 @@ class StatusWidget(ABC):
"""
return self.title
def render_status(self, context: {}) -> str:
def render_status(self, context: {}) -> str: # pylint: disable=unused-argument
"""
Render status for widget based on context
......@@ -63,16 +66,16 @@ class StatusWidget(ABC):
return self.status
@abstractmethod
def render_body(self, context: {}, request) -> str:
def render_body(self, context: {}, request) -> str: # pylint: disable=unused-argument
"""
Render body for widget based on context
:param context: Context for rendering
:param request: HTTP request (needed for rendering)
:return: Rendered widget body (HTML)
"""
pass
def render_actions(self, context: {}) -> list[dict]:
def render_actions(self, context: {}) -> list[dict]: # pylint: disable=unused-argument
"""
Render actions for widget based on context
......@@ -81,16 +84,30 @@ class StatusWidget(ABC):
:param context: Context for rendering
:return: List of actions
"""
return [a for a in self.actions]
return self.actions
class TemplateStatusWidget(StatusWidget):
"""
A :class:`StatusWidget` that produces its content by rendering a given html template
"""
@property
@abstractmethod
def template_name(self) -> str:
pass
"""
Configure the template to use
:return: name of the template to use
"""
def render_body(self, context: {}, request) -> str:
"""
Render the body of the widget using the template rendering method from django
(load and render template using the provided context)
:param context: context to use for rendering
:param request: HTTP request (needed by django)
:return: rendered content (HTML)
"""
template = loader.get_template(self.template_name)
return template.render(context, request)
......@@ -98,6 +115,8 @@ class TemplateStatusWidget(StatusWidget):
class StatusManager:
"""
Registry for all status widgets
Allows to register status widgets using the `@status_manager.register(name="xyz")` decorator
"""
widgets = {}
widgets_by_context_type = defaultdict(list)
......@@ -131,6 +150,9 @@ class StatusManager:
class StatusView(ABC, AdminViewMixin, TemplateView):
"""
Abstract view: A generic base view to create a status page holding multiple widgets
"""
template_name = "admin/AKModel/status/status.html"
@property
......@@ -139,12 +161,15 @@ class StatusView(ABC, AdminViewMixin, TemplateView):
"""
Which model/context is provided by this status view?
"""
pass
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
from AKModel.metaviews import status_manager
context['widgets'] = [w.render(context, self.request) for w in status_manager.get_by_context_type(self.provided_context_type)]
# Load status manager (local import to prevent cyclic import)
from AKModel.metaviews import status_manager # pylint: disable=import-outside-toplevel
# Render all widgets and provide them as part of the context
context['widgets'] = [w.render(context, self.request)
for w in status_manager.get_by_context_type(self.provided_context_type)]
return self.render_to_response(context)
# Generated by Django 4.2.11 on 2024-04-21 14:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0058_alter_ak_options'),
]
operations = [
migrations.AlterField(
model_name='event',
name='interest_start',
field=models.DateTimeField(blank=True, help_text='Opening time for expression of interest. When left blank, no interest indication will be possible.', null=True, verbose_name='Interest Window Start'),
),
]
# Generated by Django 4.2.11 on 2024-04-24 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0059_interest_default'),
]
operations = [
migrations.AddField(
model_name='akorgamessage',
name='resolved',
field=models.BooleanField(default=False, help_text='This message has been resolved (no further action needed)', verbose_name='Resolved'),
),
]
# Generated by Django 4.2.13 on 2025-02-25 20:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0060_orga_message_resolved'),
]
operations = [
migrations.CreateModel(
name='AKType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Name describing the type', max_length=128, verbose_name='Name')),
('event', models.ForeignKey(help_text='Associated event', on_delete=django.db.models.deletion.CASCADE, to='AKModel.event', verbose_name='Event')),
],
options={
'verbose_name': 'AK Type',
'verbose_name_plural': 'AK Types',
'ordering': ['name'],
'unique_together': {('event', 'name')},
},
),
migrations.AddField(
model_name='ak',
name='types',
field=models.ManyToManyField(blank=True, help_text='This AK is', to='AKModel.aktype', verbose_name='Types'),
),
]
# Generated by Django 4.2.13 on 2025-02-26 22:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0061_types'),
]
operations = [
migrations.RemoveField(
model_name='historicalak',
name='interest',
),
]
# Generated by Django 4.2.13 on 2025-03-03 19:59
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0062_interest_no_history'),
]
operations = [
migrations.AlterField(
model_name='ak',
name='name',
field=models.CharField(help_text='Name of the AK', max_length=256, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+'), django.core.validators.RegexValidator(message='Must contain at least one letter or digit', regex='[\\w\\s]+')], verbose_name='Name'),
),
migrations.AlterField(
model_name='ak',
name='short_name',
field=models.CharField(blank=True, help_text='Name displayed in the schedule', max_length=64, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+')], verbose_name='Short Name'),
),
migrations.AlterField(
model_name='akowner',
name='name',
field=models.CharField(help_text='Name to identify an AK owner by', max_length=64, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+'), django.core.validators.RegexValidator(message='Must contain at least one letter or digit', regex='[\\w\\s]+')], verbose_name='Nickname'),
),
migrations.AlterField(
model_name='historicalak',
name='name',
field=models.CharField(help_text='Name of the AK', max_length=256, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+'), django.core.validators.RegexValidator(message='Must contain at least one letter or digit', regex='[\\w\\s]+')], verbose_name='Name'),
),
migrations.AlterField(
model_name='historicalak',
name='short_name',
field=models.CharField(blank=True, help_text='Name displayed in the schedule', max_length=64, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+')], verbose_name='Short Name'),
),
]
import itertools
from datetime import timedelta
from datetime import datetime, timedelta
from django.db import models
from django.core.validators import RegexValidator
from django.apps import apps
from django.db import models
from django.db.models import Count
from django.urls import reverse_lazy
from django.utils import timezone
from django.utils.datetime_safe import datetime
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from simple_history.models import HistoricalRecords
from timezone_field import TimeZoneField
# Custom validators to be used for some of the fields
# Prevent inclusion of the quotation marks ' " ´ `
# This may be necessary to prevent javascript issues
no_quotation_marks_validator = RegexValidator(regex=r"['\"´`]+", inverse_match=True,
message=_('May not contain quotation marks'))
# Enforce that the field contains of at least one letter or digit (and not just special characters
# This prevents issues when autogenerating slugs from that field
slugable_validator = RegexValidator(regex=r"[\w\s]+", message=_('Must contain at least one letter or digit'))
class Event(models.Model):
""" An event supplies the frame for all Aks.
"""
An event supplies the frame for all Aks.
"""
name = models.CharField(max_length=64, unique=True, verbose_name=_('Name'),
help_text=_('Name or iteration of the event'))
......@@ -31,7 +42,10 @@ class Event(models.Model):
help_text=_('When should AKs with intention to submit a resolution be done?'))
interest_start = models.DateTimeField(verbose_name=_('Interest Window Start'), blank=True, null=True,
help_text=_('Opening time for expression of interest.'))
help_text=
_('Opening time for expression of interest. When left blank, no interest '
'indication will be possible.'))
interest_end = models.DateTimeField(verbose_name=_('Interest Window End'), blank=True, null=True,
help_text=_('Closing time for expression of interest.'))
......@@ -42,7 +56,7 @@ class Event(models.Model):
plan_hidden = models.BooleanField(verbose_name=_('Plan Hidden'), help_text=_('Hides plan for non-staff users'),
default=True)
plan_published_at = models.DateTimeField(verbose_name=_('Plan published at'), blank=True, null=True,
help_text=_('Timestamp at which the plan was published'))
help_text=_('Timestamp at which the plan was published'))
base_url = models.URLField(verbose_name=_("Base URL"), help_text=_("Prefix for wiki link construction"), blank=True)
wiki_export_template_name = models.CharField(verbose_name=_("Wiki Export Template Name"), blank=True, max_length=50)
......@@ -50,8 +64,8 @@ class Event(models.Model):
help_text=_('Default length in hours that is assumed for AKs in this event.'))
contact_email = models.EmailField(verbose_name=_("Contact email address"), blank=True,
help_text=_(
"An email address that is displayed on every page and can be used for all kinds of questions"))
help_text=_("An email address that is displayed on every page "
"and can be used for all kinds of questions"))
class Meta:
verbose_name = _('Event')
......@@ -63,25 +77,37 @@ class Event(models.Model):
@staticmethod
def get_by_slug(slug):
"""
Get event by its slug
:param slug: slug of the event
:return: event identified by the slug
:rtype: Event
"""
return Event.objects.get(slug=slug)
@staticmethod
def get_next_active():
# Get first active event taking place
"""
Get first active event taking place
:return: matching event (if any) or None
:rtype: Event
"""
event = Event.objects.filter(active=True).order_by('start').first()
# No active event? Return the next event taking place
if event is None:
event = Event.objects.order_by('start').filter(start__gt=datetime.now()).first()
event = Event.objects.order_by('start').filter(start__gt=datetime.now().astimezone()).first()
return event
def get_categories_with_aks(self, wishes_seperately=False, filter=lambda ak: True, hide_empty_categories=False):
def get_categories_with_aks(self, wishes_seperately=False,
filter_func=lambda ak: True, hide_empty_categories=False):
"""
Get AKCategories as well as a list of AKs belonging to the category for this event
:param wishes_seperately: Return wishes as individual list.
:type wishes_seperately: bool
:param filter: Optional filter predicate, only include AK in list if filter returns True
:type filter: (AK)->bool
:param filter_func: Optional filter predicate, only include AK in list if filter returns True
:type filter_func: (AK)->bool
:return: list of category-AK-list-tuples, optionally the additional list of AK wishes
:rtype: list[(AKCategory, list[AK])] [, list[AK]]
"""
......@@ -89,11 +115,26 @@ class Event(models.Model):
categories_with_aks = []
ak_wishes = []
# Fill lists by iterating
# A different behavior is needed depending on whether wishes should show up inside their categories
# or as a separate category
def _get_category_aks(category):
"""
Get all AKs belonging to a category
Use joining and prefetching to reduce the number of necessary SQL queries
:param category: category the AKs should belong to
:return: QuerySet over AKs
:return: QuerySet[AK]
"""
return category.ak_set.select_related('event').prefetch_related('owners', 'akslot_set').all()
if wishes_seperately:
for category in categories:
ak_list = []
for ak in category.ak_set.select_related('event').prefetch_related('owners', 'akslot_set').all():
if filter(ak):
for ak in _get_category_aks(category):
if filter_func(ak):
if ak.wish:
ak_wishes.append(ak)
else:
......@@ -101,27 +142,44 @@ class Event(models.Model):
if not hide_empty_categories or len(ak_list) > 0:
categories_with_aks.append((category, ak_list))
return categories_with_aks, ak_wishes
else:
for category in categories:
ak_list = []
for ak in category.ak_set.all():
if filter(ak):
ak_list.append(ak)
if not hide_empty_categories or len(ak_list) > 0:
categories_with_aks.append((category, ak_list))
return categories_with_aks
for category in categories:
ak_list = []
for ak in _get_category_aks(category):
if filter_func(ak):
ak_list.append(ak)
if not hide_empty_categories or len(ak_list) > 0:
categories_with_aks.append((category, ak_list))
return categories_with_aks
def get_unscheduled_wish_slots(self):
"""
Get all slots of wishes that are currently not scheduled
:return: queryset of theses slots
:rtype: QuerySet[AKSlot]
"""
return self.akslot_set.filter(start__isnull=True).annotate(Count('ak__owners')).filter(ak__owners__count=0)
def get_aks_without_availabilities(self):
return self.ak_set.annotate(Count('availabilities', distinct=True)).annotate(Count('owners', distinct=True)).filter(availabilities__count=0, owners__count__gt=0)
"""
Gt all AKs that don't have any availability at all
:return: generator over these AKs
:rtype: Generator[AK]
"""
return (self.ak_set
.annotate(Count('availabilities', distinct=True))
.annotate(Count('owners', distinct=True))
.filter(availabilities__count=0, owners__count__gt=0)
)
class AKOwner(models.Model):
""" An AKOwner describes the person organizing/holding an AK.
"""
name = models.CharField(max_length=64, verbose_name=_('Nickname'), help_text=_('Name to identify an AK owner by'))
name = models.CharField(max_length=64, verbose_name=_('Nickname'),
validators=[no_quotation_marks_validator, slugable_validator],
help_text=_('Name to identify an AK owner by'))
slug = models.SlugField(max_length=64, blank=True, verbose_name=_('Slug'), help_text=_('Slug for URL generation'))
institution = models.CharField(max_length=128, blank=True, verbose_name=_('Institution'), help_text=_('Uni etc.'))
link = models.URLField(blank=True, verbose_name=_('Web Link'), help_text=_('Link to Homepage'))
......@@ -141,21 +199,34 @@ class AKOwner(models.Model):
return self.name
def _generate_slug(self):
"""
Auto-generate a slug for an owner
This will start with a very simple slug (the name truncated to a maximum length) and then gradually produce
more complicated slugs when the previous candidates are already used
:return: the slug
:rtype: str
"""
max_length = self._meta.get_field('slug').max_length
# Try name alone (truncated if necessary)
slug_candidate = slugify(self.name)[:max_length]
if not AKOwner.objects.filter(event=self.event, slug=slug_candidate).exists():
self.slug = slug_candidate
return
# Try name and institution separated by '_' (truncated if necessary)
slug_candidate = slugify(slug_candidate + '_' + self.institution)[:max_length]
if not AKOwner.objects.filter(event=self.event, slug=slug_candidate).exists():
self.slug = slug_candidate
return
# Try name + institution + an incrementing digit
for i in itertools.count(1):
if not AKOwner.objects.filter(event=self.event, slug=slug_candidate).exists():
break
digits = len(str(i))
slug_candidate = '{}-{}'.format(slug_candidate[:-(digits + 1)], i)
slug_candidate = f'{slug_candidate[:-(digits + 1)]}-{i}'
self.slug = slug_candidate
......@@ -167,6 +238,15 @@ class AKOwner(models.Model):
@staticmethod
def get_by_slug(event, slug):
"""
Get owner by slug
Will be identified by the combination of event slug and owner slug which is unique
:param event: event
:param slug: slug of the owner
:return: owner identified by slugs
:rtype: AKOwner
"""
return AKOwner.objects.get(event=event, slug=slug)
......@@ -178,8 +258,8 @@ class AKCategory(models.Model):
description = models.TextField(blank=True, verbose_name=_("Description"),
help_text=_("Short description of this AK Category"))
present_by_default = models.BooleanField(blank=True, default=True, verbose_name=_("Present by default"),
help_text=_(
"Present AKs of this category by default if AK owner did not specify whether this AK should be presented?"))
help_text=_("Present AKs of this category by default if AK owner did not "
"specify whether this AK should be presented?"))
event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'),
help_text=_('Associated event'))
......@@ -213,6 +293,11 @@ class AKTrack(models.Model):
return self.name
def aks_with_category(self):
"""
Get all AKs that belong to this track with category already joined to prevent additional SQL queries
:return: queryset over the AKs
:rtype: QuerySet[AK]
"""
return self.ak_set.select_related('category').all()
......@@ -234,23 +319,46 @@ class AKRequirement(models.Model):
return self.name
class AKType(models.Model):
""" An AKType allows to associate one or multiple types with an AK, e.g., to better describe the format of that AK
or to which group of people it is addressed. Types are specified per event and are an optional feature.
"""
name = models.CharField(max_length=128, verbose_name=_('Name'), help_text=_('Name describing the type'))
event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'),
help_text=_('Associated event'))
class Meta:
verbose_name = _('AK Type')
verbose_name_plural = _('AK Types')
ordering = ['name']
unique_together = ['event', 'name']
def __str__(self):
return self.name
class AK(models.Model):
""" An AK is a slot-based activity to be scheduled during an event.
"""
name = models.CharField(max_length=256, verbose_name=_('Name'), help_text=_('Name of the AK'))
name = models.CharField(max_length=256, verbose_name=_('Name'), help_text=_('Name of the AK'),
validators=[no_quotation_marks_validator, slugable_validator])
short_name = models.CharField(max_length=64, blank=True, verbose_name=_('Short Name'),
validators=[no_quotation_marks_validator],
help_text=_('Name displayed in the schedule'))
description = models.TextField(blank=True, verbose_name=_('Description'), help_text=_('Description of the AK'))
owners = models.ManyToManyField(to=AKOwner, blank=True, verbose_name=_('Owners'),
help_text=_('Those organizing the AK'))
# TODO generate automatically
# Will be automatically generated in save method if not set
link = models.URLField(blank=True, verbose_name=_('Web Link'), help_text=_('Link to wiki page'))
protocol_link = models.URLField(blank=True, verbose_name=_('Protocol Link'), help_text=_('Link to protocol'))
category = models.ForeignKey(to=AKCategory, on_delete=models.PROTECT, verbose_name=_('Category'),
help_text=_('Category of the AK'))
types = models.ManyToManyField(to=AKType, blank=True, verbose_name=_('Types'),
help_text=_("This AK is"))
track = models.ForeignKey(to=AKTrack, blank=True, on_delete=models.SET_NULL, null=True, verbose_name=_('Track'),
help_text=_('Track the AK belongs to'))
......@@ -268,7 +376,8 @@ class AK(models.Model):
help_text=_('AKs that should precede this AK in the schedule'))
notes = models.TextField(blank=True, verbose_name=_('Organizational Notes'), help_text=_(
'Notes to organizers. These are public. For private notes, please use the button for private messages on the detail page of this AK (after creation/editing).'))
'Notes to organizers. These are public. For private notes, please use the button for private messages '
'on the detail page of this AK (after creation/editing).'))
interest = models.IntegerField(default=-1, verbose_name=_('Interest'), help_text=_('Expected number of people'))
interest_counter = models.IntegerField(default=0, verbose_name=_('Interest Counter'),
......@@ -280,7 +389,7 @@ class AK(models.Model):
include_in_export = models.BooleanField(default=True, verbose_name=_('Export?'),
help_text=_("Include AK in wiki export?"))
history = HistoricalRecords(excluded_fields=['interest_counter', 'include_in_export'])
history = HistoricalRecords(excluded_fields=['interest', 'interest_counter', 'include_in_export'])
class Meta:
verbose_name = _('AK')
......@@ -295,52 +404,132 @@ class AK(models.Model):
@property
def details(self):
"""
Generate a detailed string representation, e.g., for usage in scheduling
:return: string representation of that AK with all details
:rtype: str
"""
# local import to prevent cyclic import
# pylint: disable=import-outside-toplevel
from AKModel.availability.models import Availability
availabilities = ', \n'.join(f'{a.simplified}' for a in Availability.objects.select_related('event').filter(ak=self))
return f"""{self.name}{" (R)" if self.reso else ""}:
availabilities = ', \n'.join(f'{a.simplified}' for a in Availability.objects.select_related('event')
.filter(ak=self))
detail_string = f"""{self.name}{" (R)" if self.reso else ""}:
{self.owners_list}
{_('Interest')}: {self.interest}
{_("Requirements")}: {", ".join(str(r) for r in self.requirements.all())}
{_("Conflicts")}: {", ".join(str(c) for c in self.conflicts.all())}
{_("Prerequisites")}: {", ".join(str(p) for p in self.prerequisites.all())}
{_("Availabilities")}: \n{availabilities}"""
{_('Interest')}: {self.interest}"""
if self.requirements.count() > 0:
detail_string += f"\n{_('Requirements')}: {', '.join(str(r) for r in self.requirements.all())}"
if self.types.count() > 0:
detail_string += f"\n{_('Types')}: {', '.join(str(r) for r in self.types.all())}"
# Find conflicts
# (both directions, those specified for this AK and those were this AK was specified as conflict)
# Deduplicate and order list alphabetically
conflicts = set()
if self.conflicts.count() > 0:
for c in self.conflicts.all():
conflicts.add(str(c))
if self.conflict.count() > 0:
for c in self.conflict.all():
conflicts.add(str(c))
if len(conflicts) > 0:
conflicts = list(conflicts)
conflicts.sort()
detail_string += f"\n{_('Conflicts')}: {', '.join(conflicts)}"
if self.prerequisites.count() > 0:
detail_string += f"\n{_('Prerequisites')}: {', '.join(str(p) for p in self.prerequisites.all())}"
detail_string += f"\n{_('Availabilities')}: \n{availabilities}"
return detail_string
@property
def owners_list(self):
"""
Get a list of stringified representations of all owners
:return: list of owners
:rtype: List[str]
"""
return ", ".join(str(owner) for owner in self.owners.all())
@property
def durations_list(self):
"""
Get a list of stringified representations of all durations of associated slots
:return: list of durations
:rtype: List[str]
"""
return ", ".join(str(slot.duration_simplified) for slot in self.akslot_set.select_related('event').all())
@property
def wish(self):
"""
Is the AK a wish?
:return: true if wish, false if not
:rtype: bool
"""
return self.owners.count() == 0
def increment_interest(self):
"""
Increment the interest counter for this AK by one
without tracking that change to prevent an unreadable and large history
"""
self.interest_counter += 1
self.skip_history_when_saving = True
self.skip_history_when_saving = True # pylint: disable=attribute-defined-outside-init
self.save()
del self.skip_history_when_saving
@property
def availabilities(self):
"""
Get all availabilities associated to this AK
:return: availabilities
:rtype: QuerySet[Availability]
"""
return "Availability".objects.filter(ak=self)
@property
def edit_url(self):
"""
Get edit URL for this AK
Will link to frontend if AKSubmission is active, otherwise to the edit view for this object in admin interface
:return: URL
:rtype: str
"""
if apps.is_installed("AKSubmission"):
return reverse_lazy('submit:ak_edit', kwargs={'event_slug': self.event.slug, 'pk': self.id})
return reverse_lazy('admin:AKModel_ak_change', kwargs={'object_id': self.id})
@property
def detail_url(self):
"""
Get detail URL for this AK
Will link to frontend if AKSubmission is active, otherwise to the edit view for this object in admin interface
:return: URL
:rtype: str
"""
if apps.is_installed("AKSubmission"):
return reverse_lazy('submit:ak_detail', kwargs={'event_slug': self.event.slug, 'pk': self.id})
return self.edit_url
def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None):
# Auto-Generate Link if not set yet
if self.link == "":
link = self.event.base_url + self.name.replace(" ", "_")
# Truncate links longer than 200 characters (default length of URL fields in django)
self.link = link[:200]
# Tell Django that we have updated the link field
if update_fields is not None:
update_fields = {"link"}.union(update_fields)
super().save(*args,
force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
class Room(models.Model):
""" A room describes where an AK can be held.
......@@ -364,6 +553,12 @@ class Room(models.Model):
@property
def title(self):
"""
Get title of a room, which consists of location and name if location is set, otherwise only the name
:return: title
:rtype: str
"""
if self.location:
return f"{self.location} {self.name}"
return self.name
......@@ -429,7 +624,8 @@ class AKSlot(models.Model):
start = self.start.astimezone(self.event.timezone)
end = self.end.astimezone(self.event.timezone)
return f"{start.strftime('%a %H:%M')} - {end.strftime('%H:%M') if start.day == end.day else end.strftime('%a %H:%M')}"
return (f"{start.strftime('%a %H:%M')} - "
f"{end.strftime('%H:%M') if start.day == end.day else end.strftime('%a %H:%M')}")
@property
def end(self):
......@@ -448,10 +644,29 @@ class AKSlot(models.Model):
return (timezone.now() - self.updated).total_seconds()
def overlaps(self, other: "AKSlot"):
"""
Check whether two slots overlap
:param other: second slot to compare with
:return: true if they overlap, false if not:
:rtype: bool
"""
return self.start < other.end <= self.end or self.start <= other.start < self.end
def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None):
# Make sure duration is not longer than the event
if update_fields is None or 'duration' in update_fields:
event_duration = self.event.end - self.event.start
event_duration_hours = event_duration.days * 24 + event_duration.seconds // 3600
self.duration = min(self.duration, event_duration_hours)
super().save(*args,
force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
class AKOrgaMessage(models.Model):
"""
Model representing confidential messages to the organizers/scheduling people, belonging to a certain AK
"""
ak = models.ForeignKey(to=AK, on_delete=models.CASCADE, verbose_name=_('AK'),
help_text=_('AK this message belongs to'))
text = models.TextField(verbose_name=_("Message text"),
......@@ -459,6 +674,8 @@ class AKOrgaMessage(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'),
help_text=_('Associated event'))
resolved = models.BooleanField(verbose_name=_('Resolved'), default=False,
help_text=_('This message has been resolved (no further action needed)'))
class Meta:
verbose_name = _('AK Orga Message')
......@@ -470,12 +687,24 @@ class AKOrgaMessage(models.Model):
class ConstraintViolation(models.Model):
"""
Model to represent any kind of constraint violation
Can have two different severities: violation and warning
The list of possible types is defined in :class:`ViolationType`
Depending on the type, different fields (references to other models) will be filled. Each violation should always
be related to an event and at least on other instance of a causing entity
"""
class Meta:
verbose_name = _('Constraint Violation')
verbose_name_plural = _('Constraint Violations')
ordering = ['-timestamp']
class ViolationType(models.TextChoices):
"""
Possible types of violations with their text representation
"""
OWNER_TWO_SLOTS = 'ots', _('Owner has two parallel slots')
SLOT_OUTSIDE_AVAIL = 'soa', _('AK Slot was scheduled outside the AK\'s availabilities')
ROOM_TWO_SLOTS = 'rts', _('Room has two AK slots scheduled at the same time')
......@@ -483,13 +712,16 @@ class ConstraintViolation(models.Model):
AK_CONFLICT_COLLISION = 'acc', _('AK Slot is scheduled at the same time as an AK listed as a conflict')
AK_BEFORE_PREREQUISITE = 'abp', _('AK Slot is scheduled before an AK listed as a prerequisite')
AK_AFTER_RESODEADLINE = 'aar', _(
'AK Slot for AK with intention to submit a resolution is scheduled after resolution deadline')
'AK Slot for AK with intention to submit a resolution is scheduled after resolution deadline')
AK_CATEGORY_MISMATCH = 'acm', _('AK Slot in a category is outside that categories availabilities')
AK_SLOT_COLLISION = 'asc', _('Two AK Slots for the same AK scheduled at the same time')
ROOM_CAPACITY_EXCEEDED = 'rce', _('Room does not have enough space for interest in scheduled AK Slot')
SLOT_OUTSIDE_EVENT = 'soe', _('AK Slot is scheduled outside the event\'s availabilities')
class ViolationLevel(models.IntegerChoices):
"""
Possible severities/levels of a CV
"""
WARNING = 1, _('Warning')
VIOLATION = 10, _('Violation')
......@@ -501,6 +733,7 @@ class ConstraintViolation(models.Model):
event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'),
help_text=_('Associated event'))
# Possible "causes":
aks = models.ManyToManyField(to=AK, blank=True, verbose_name=_('AKs'),
help_text=_('AK(s) belonging to this constraint'))
ak_slots = models.ManyToManyField(to=AKSlot, blank=True, verbose_name=_('AK Slots'),
......@@ -551,22 +784,37 @@ class ConstraintViolation(models.Model):
@property
def details(self):
"""
Property: Details
"""
return self.get_details()
@property
def edit_url(self):
def edit_url(self) -> str:
"""
Property: Edit URL for this CV
"""
return reverse_lazy('admin:AKModel_constraintviolation_change', kwargs={'object_id': self.pk})
@property
def level_display(self):
def level_display(self) -> str:
"""
Property: Severity as string
"""
return self.get_level_display()
@property
def type_display(self):
def type_display(self) -> str:
"""
Property: Type as string
"""
return self.get_type_display()
@property
def timestamp_display(self):
def timestamp_display(self) -> str:
"""
Property: Creation timestamp as string
"""
return self.timestamp.astimezone(self.event.timezone).strftime('%d.%m.%y %H:%M')
@property
......@@ -585,7 +833,10 @@ class ConstraintViolation(models.Model):
return self.aks_tmp
@property
def _aks_str(self):
def _aks_str(self) -> str:
"""
Property: AKs as string
"""
if self.pk and self.pk > 0:
return ', '.join(str(a) for a in self.aks.all())
return ', '.join(str(a) for a in self.aks_tmp)
......@@ -606,7 +857,10 @@ class ConstraintViolation(models.Model):
return self.ak_slots_tmp
@property
def _ak_slots_str(self):
def _ak_slots_str(self) -> str:
"""
Property: Slots as string
"""
if self.pk and self.pk > 0:
return ', '.join(str(a) for a in self.ak_slots.select_related('event').all())
return ', '.join(str(a) for a in self.ak_slots_tmp)
......@@ -655,6 +909,11 @@ class ConstraintViolation(models.Model):
class DefaultSlot(models.Model):
"""
Model representing a default slot,
i.e., a prefered slot to use for typical AKs in the schedule to guarantee enough breaks etc.
"""
class Meta:
verbose_name = _('Default Slot')
verbose_name_plural = _('Default Slots')
......@@ -667,22 +926,35 @@ class DefaultSlot(models.Model):
help_text=_('Associated event'))
primary_categories = models.ManyToManyField(to=AKCategory, verbose_name=_('Primary categories'), blank=True,
help_text=_('Categories that should be assigned to this slot primarily'))
help_text=_(
'Categories that should be assigned to this slot primarily'))
@property
def start_simplified(self):
def start_simplified(self) -> str:
"""
Property: Simplified version of the start timetstamp (weekday, hour, minute) as string
"""
return self.start.astimezone(self.event.timezone).strftime('%a %H:%M')
@property
def start_iso(self):
def start_iso(self) -> str:
"""
Property: Start timestamp as ISO timestamp for usage in calendar views
"""
return timezone.localtime(self.start, self.event.timezone).strftime("%Y-%m-%dT%H:%M:%S")
@property
def end_simplified(self):
def end_simplified(self) -> str:
"""
Property: Simplified version of the end timetstamp (weekday, hour, minute) as string
"""
return self.end.astimezone(self.event.timezone).strftime('%a %H:%M')
@property
def end_iso(self):
def end_iso(self) -> str:
"""
Property: End timestamp as ISO timestamp for usage in calendar views
"""
return timezone.localtime(self.end, self.event.timezone).strftime("%Y-%m-%dT%H:%M:%S")
def __str__(self):
......
......@@ -4,36 +4,54 @@ from AKModel.models import AK, Room, AKSlot, AKTrack, AKCategory, AKOwner
class AKOwnerSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKOwner
"""
class Meta:
model = AKOwner
fields = '__all__'
class AKCategorySerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKCategory
"""
class Meta:
model = AKCategory
fields = '__all__'
class AKTrackSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKTrack
"""
class Meta:
model = AKTrack
fields = '__all__'
class AKSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AK
"""
class Meta:
model = AK
fields = '__all__'
class RoomSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for Room
"""
class Meta:
model = Room
fields = '__all__'
class AKSlotSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKSlot
"""
class Meta:
model = AKSlot
fields = '__all__'
......@@ -41,6 +59,9 @@ class AKSlotSerializer(serializers.ModelSerializer):
treat_as_local = serializers.BooleanField(required=False, default=False, write_only=True)
def create(self, validated_data:dict):
# Handle timezone adaption based upon the control field "treat_as_local":
# If it is set, ignore timezone submitted from the browser (will always be UTC)
# and treat it as input in the events timezone instead
if validated_data['treat_as_local']:
validated_data['start'] = validated_data['start'].replace(tzinfo=None).astimezone(
validated_data['event'].timezone)
......
from django.contrib.admin import AdminSite
from django.utils.translation import gettext_lazy as _
# from django.urls import path
from AKModel.models import Event
class AKAdminSite(AdminSite):
"""
Custom admin interface definition (extend the admin functionality of Django)
"""
index_template = "admin/ak_index.html"
site_header = f"AKPlanning - {_('Administration')}"
index_title = _('Administration')
def get_urls(self):
from django.urls import path
"""
Get URLs -- add further views that are not related to a certain model here if needed
"""
urls = super().get_urls()
urls += [
# path('...', self.admin_view(...)),
......@@ -19,6 +24,8 @@ class AKAdminSite(AdminSite):
return urls
def index(self, request, extra_context=None):
# Override index page rendering to provide extra context (the list of active events)
# to be used in the adapted template
if extra_context is None:
extra_context = {}
extra_context["active_events"] = Event.objects.filter(active=True)
......
......@@ -4,8 +4,8 @@
{% block content %}
<pre>
title;duration;who;requirements;prerequisites;conflicts;availabilities;category;track;reso;notes;
{% for slot in slots %}{{ slot.ak.short_name }};{{ slot.duration }};{{ slot.ak.owners.all|join:", " }};{{ slot.ak.requirements.all|join:", " }};{{ slot.ak.prerequisites.all|join:", " }};{{ slot.ak.conflicts.all|join:", " }};{% for a in slot.ak.availabilities.all %}{{ a.start | timezone:event.timezone | date:"l H:i" }} - {{ a.end | timezone:event.timezone | date:"l H:i" }}, {% endfor %};{{ slot.ak.category }};{{ slot.ak.track }};{{ slot.ak.reso }};{{ slot.ak.notes }};
title;duration;who;requirements;prerequisites;conflicts;availabilities;category;types;track;reso;notes;
{% for slot in slots %}{{ slot.ak.short_name }};{{ slot.duration }};{{ slot.ak.owners.all|join:", " }};{{ slot.ak.requirements.all|join:", " }};{{ slot.ak.prerequisites.all|join:", " }};{{ slot.ak.conflicts.all|join:", " }};{% for a in slot.ak.availabilities.all %}{{ a.start | timezone:event.timezone | date:"l H:i" }} - {{ a.end | timezone:event.timezone | date:"l H:i" }}, {% endfor %};{{ slot.ak.category }};{{ slot.ak.types.all|join:", " }};{{ slot.ak.track }};{{ slot.ak.reso }};{{ slot.ak.notes }};
{% endfor %}
</pre>
{% endblock %}
{% extends "admin/base_site.html" %}
{% load tags_AKModel %}
{% load i18n %}
{% load tz %}
{% load fontawesome_6 %}
{% block title %}{% trans "AKs by Owner" %}: {{owner}}{% endblock %}
{% block content %}
{% timezone event.timezone %}
<h2>[{{event}}] <a href="{% url 'admin:AKModel_akowner_change' owner.pk %}">{{owner}}</a> - {% trans "AKs" %}</h2>
<div class="row mt-4">
<table class="table table-striped">
{% for ak in owner.ak_set.all %}
<tr>
<td>{{ ak }}</td>
{% if "AKSubmission"|check_app_installed %}
<td class="text-end">
<a href="{{ ak.detail_url }}" data-bs-toggle="tooltip"
title="{% trans 'Details' %}"
class="btn btn-primary">{% fa6_icon 'info' 'fas' %}</a>
{% if event.active %}
<a href="{{ ak.edit_url }}" data-bs-toggle="tooltip"
title="{% trans 'Edit' %}"
class="btn btn-success">{% fa6_icon 'pencil-alt' 'fas' %}</a>
{% endif %}
{% endif %}
</td>
</tr>
{% empty %}
<tr><td>{% trans "This user does not have any AKs currently" %}</td></tr>
{% endfor %}
</table>
</div>
{% endtimezone %}
{% endblock %}
......@@ -8,6 +8,11 @@
{% block title %}{% trans "New event wizard" %}: {{ wizard_step_text }}{% endblock %}
{% block extrahead %}
{{ block.super }}
{{ form.media }}
{% endblock %}
{% block content %}
{% include "admin/AKModel/event_wizard/wizard_steps.html" %}
......@@ -17,8 +22,6 @@
<h5 class="mb-3">{% trans "Successfully imported.<br><br>Do you want to activate your event now?" %}</h5>
{{ form.media }}
<form method="post">{% csrf_token %}
{% bootstrap_form form %}
......
......@@ -8,6 +8,11 @@
{% block title %}{% trans "New event wizard" %}: {{ wizard_step_text }}{% endblock %}
{% block extrahead %}
{{ block.super }}
{{ form.media }}
{% endblock %}
{% block content %}
{% include "admin/AKModel/event_wizard/wizard_steps.html" %}
......@@ -29,8 +34,6 @@
<h5 class="mb-3">{% trans "Your event was created and can now be further configured." %}</h5>
{{ form.media }}
<form method="post">{% csrf_token %}
{% bootstrap_form form %}
......
......@@ -8,11 +8,14 @@
{% block title %}{% trans "New event wizard" %}: {{ wizard_step_text }}{% endblock %}
{% block extrahead %}
{{ block.super }}
{{ form.media }}
{% endblock %}
{% block content %}
{% include "admin/AKModel/event_wizard/wizard_steps.html" %}
{{ form.media }}
<form method="post">{% csrf_token %}
{% bootstrap_form form %}
......
......@@ -8,11 +8,14 @@
{% block title %}{% trans "New event wizard" %}: {{ wizard_step_text }}{% endblock %}
{% block extrahead %}
{{ block.super }}
{{ form.media }}
{% endblock %}
{% block content %}
{% include "admin/AKModel/event_wizard/wizard_steps.html" %}
{{ form.media }}
{% timezone timezone %}
<form method="post">{% csrf_token %}
......
......@@ -7,6 +7,11 @@
{% block title %}{% trans "New event wizard" %}: {{ wizard_step_text }}{% endblock %}
{% block extrahead %}
{{ block.super }}
{{ form.media }}
{% endblock %}
{% block content %}
{% include "admin/AKModel/event_wizard/wizard_steps.html" %}
......
{% load tz %}
{% load fontawesome_6 %}
{% timezone event.timezone %}
<table class="table table-striped">
......@@ -7,7 +8,10 @@
<span class="text-secondary float-end">
{{ message.timestamp|date:"Y-m-d H:i:s" }}
</span>
<h5><a href="{{ message.ak.detail_url }}">{{ message.ak }}</a></h5>
<h5><a href="{{ message.ak.detail_url }}">
{% if message.resolved %}{% fa6_icon "check-circle" %} {% endif %}
{{ message.ak }}
</a></h5>
<p>{{ message.text }}</p>
</td></tr>
{% endfor %}
......
......@@ -3,35 +3,65 @@ from django.apps import apps
from django.conf import settings
from django.utils.html import format_html, mark_safe, conditional_escape
from django.templatetags.static import static
from django.template.defaultfilters import date
from fontawesome_6.app_settings import get_css
from AKModel.models import Event
register = template.Library()
# Get Footer Info from settings
@register.simple_tag
def footer_info():
"""
Get Footer Info from settings
:return: a dict of several strings like the impress URL to use in the footer
:rtype: Dict[str, str]
"""
return settings.FOOTER_INFO
@register.filter
def check_app_installed(name):
"""
Check whether the app with the given name is active in this instance
:param name: name of the app to check for
:return: true if app is installed
:rtype: bool
"""
return apps.is_installed(name)
@register.filter
def message_bootstrap_class(tag):
"""
Turn message severity classes into corresponding bootstrap css classes
:param tag: severity of the message
:return: matching bootstrap class
"""
if tag == "error":
return "alert-danger"
elif tag == "success":
if tag == "success":
return "alert-success"
elif tag == "warning":
if tag == "warning":
return "alert-warning"
return "alert-info"
@register.filter
def wiki_owners_export(owners, event):
"""
Preserve owner link information for wiki export by using internal links if possible
but external links when owner specified a non-wikilink. This is applied to the full list of owners
:param owners: list of owners
:param event: event this owner belongs to and that is currently exported (specifying this directly prevents unnecessary database lookups) #pylint: disable=line-too-long
:return: linkified owners list in wiki syntax
:rtype: str
"""
def to_link(owner):
if owner.link != '':
event_link_prefix, _ = event.base_url.rsplit("/", 1)
......@@ -44,17 +74,45 @@ def wiki_owners_export(owners, event):
return ", ".join(to_link(owner) for owner in owners.all())
@register.filter
def event_month_year(event:Event):
"""
Print rough event date (month and year)
:param event: event to print the date for
:return: string containing rough date information for event
"""
if event.start.month == event.end.month:
return f"{date(event.start, 'F')} {event.start.year}"
event_start_string = date(event.start, 'F')
if event.start.year != event.end.year:
event_start_string = f"{event_start_string} {event.start.year}"
return f"{event_start_string} - {date(event.end, 'F')} {event.end.year}"
# get list of relevant css fontawesome css files for this instance
css = get_css()
@register.simple_tag
def fontawesome_6_css():
"""
Create html code to load all required fontawesome css files
:return: HTML code to load css
:rtype: str
"""
return mark_safe(conditional_escape('\n').join(format_html(
'<link href="{}" rel="stylesheet" media="all">', stylesheet) for stylesheet in css))
@register.simple_tag
def fontawesome_6_js():
"""
Create html code to load all required fontawesome javascript files
:return: HTML code to load js
:rtype: str
"""
return mark_safe(format_html(
'<script type="text/javascript" src="{}"></script>', static('fontawesome_6/js/django-fontawesome.js')
))
\ No newline at end of file
))
import traceback
from typing import List
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.contrib.messages.storage.base import Message
from django.test import TestCase
......@@ -12,21 +12,43 @@ from AKModel.models import Event, AKOwner, AKCategory, AKTrack, AKRequirement, A
class BasicViewTests:
"""
Parent class for "standard" tests of views
Provided with a list of views and arguments (if necessary), this will test that views
- render correctly without errors
- are only reachable with the correct rights (neither too freely nor too restricted)
To do this, the test creates sample users, fixtures are loaded automatically by the django test framework.
It also provides helper functions, e.g., to check for correct messages to the user or more simply generate
the URLs to test
In this class, methods from :class:`TestCase` will be called at multiple places event though TestCase is not a
parent of this class but has to be included as parent in concrete implementations of this class seperately.
It however still makes sense to treat this class as some kind of mixin and not implement it as a child of TestCase,
since the test framework does not understand the concept of abstract test definitions and would handle this class
as real test case otherwise, distorting the test results.
"""
# pylint: disable=no-member
VIEWS = []
APP_NAME = ''
VIEWS_STAFF_ONLY = []
EDIT_TESTCASES = []
def setUp(self):
self.staff_user = User.objects.create(
def setUp(self): # pylint: disable=invalid-name
"""
Setup testing by creating sample users
"""
user_model = get_user_model()
self.staff_user = user_model.objects.create(
username='Test Staff User', email='teststaff@example.com', password='staffpw',
is_staff=True, is_active=True
)
self.admin_user = User.objects.create(
self.admin_user = user_model.objects.create(
username='Test Admin User', email='testadmin@example.com', password='adminpw',
is_staff=True, is_superuser=True, is_active=True
)
self.deactivated_user = User.objects.create(
self.deactivated_user = user_model.objects.create(
username='Test Deactivated User', email='testdeactivated@example.com', password='deactivatedpw',
is_staff=True, is_active=False
)
......@@ -45,6 +67,13 @@ class BasicViewTests:
return view_name_with_prefix, url
def _assert_message(self, response, expected_message, msg_prefix=""):
"""
Assert that the correct message is shown and cause test to fail if not
:param response: response to check
:param expected_message: message that should be shown
:param msg_prefix: prefix for the error message when test fails
"""
messages:List[Message] = list(get_messages(response.wsgi_request))
msg_count = "No message shown to user"
......@@ -59,60 +88,83 @@ class BasicViewTests:
self.assertEqual(messages[-1].message, expected_message, msg=msg_content)
def test_views_for_200(self):
"""
Test the list of public views (as specified in "VIEWS") for error-free rendering
"""
for view_name in self.VIEWS:
view_name_with_prefix, url = self._name_and_url(view_name)
try:
response = self.client.get(url)
self.assertEqual(response.status_code, 200, msg=f"{view_name_with_prefix} ({url}) broken")
except Exception as e:
self.fail(f"An error occurred during rendering of {view_name_with_prefix} ({url}):\n\n{traceback.format_exc()}")
except Exception: # pylint: disable=broad-exception-caught
self.fail(f"An error occurred during rendering of {view_name_with_prefix} ({url}):"
f"\n\n{traceback.format_exc()}")
def test_access_control_staff_only(self):
"""
Test whether internal views (as specified in "VIEWS_STAFF_ONLY" are visible to staff users and staff users only
"""
# Not logged in? Views should not be visible
self.client.logout()
for view_name in self.VIEWS_STAFF_ONLY:
view_name_with_prefix, url = self._name_and_url(view_name)
for view_name_info in self.VIEWS_STAFF_ONLY:
expected_response_code = 302 if len(view_name_info) == 2 else view_name_info[2]
view_name_with_prefix, url = self._name_and_url(view_name_info)
response = self.client.get(url)
self.assertEqual(response.status_code, 302, msg=f"{view_name_with_prefix} ({url}) accessible by non-staff")
self.assertEqual(response.status_code, expected_response_code,
msg=f"{view_name_with_prefix} ({url}) accessible by non-staff")
# Logged in? Views should be visible
self.client.force_login(self.staff_user)
for view_name in self.VIEWS_STAFF_ONLY:
view_name_with_prefix, url = self._name_and_url(view_name)
for view_name_info in self.VIEWS_STAFF_ONLY:
view_name_with_prefix, url = self._name_and_url(view_name_info)
try:
response = self.client.get(url)
self.assertEqual(response.status_code, 200,
msg=f"{view_name_with_prefix} ({url}) should be accessible for staff (but isn't)")
except Exception as e:
self.fail(f"An error occurred during rendering of {view_name_with_prefix} ({url}):\n\n{traceback.format_exc()}")
except Exception: # pylint: disable=broad-exception-caught
self.fail(f"An error occurred during rendering of {view_name_with_prefix} ({url}):"
f"\n\n{traceback.format_exc()}")
# Disabled user? Views should not be visible
self.client.force_login(self.deactivated_user)
for view_name in self.VIEWS_STAFF_ONLY:
view_name_with_prefix, url = self._name_and_url(view_name)
for view_name_info in self.VIEWS_STAFF_ONLY:
expected_response_code = 302 if len(view_name_info) == 2 else view_name_info[2]
view_name_with_prefix, url = self._name_and_url(view_name_info)
response = self.client.get(url)
self.assertEqual(response.status_code, 302,
self.assertEqual(response.status_code, expected_response_code,
msg=f"{view_name_with_prefix} ({url}) still accessible for deactivated user")
def _to_sendable_value(self, v):
def _to_sendable_value(self, val):
"""
Create representation sendable via POST from form data
:param v: value to prepare
:type v: any
Needed to automatically check create, update and delete views
:param val: value to prepare
:type val: any
:return: prepared value (normally either raw value or primary key of complex object)
"""
if type(v) == list:
return [e.pk for e in v]
if type(v) == "RelatedManager":
return [e.pk for e in v.all()]
return v
if isinstance(val, list):
return [e.pk for e in val]
if type(val) == "RelatedManager": # pylint: disable=unidiomatic-typecheck
return [e.pk for e in val.all()]
return val
def test_submit_edit_form(self):
"""
Test edit forms in the most simple way (sending them again unchanged)
Test edit forms (as specified in "EDIT_TESTCASES") in the most simple way (sending them again unchanged)
"""
for testcase in self.EDIT_TESTCASES:
self._test_submit_edit_form(testcase)
def _test_submit_edit_form(self, testcase):
"""
Test a single edit form by rendering and sending it again unchanged
This will test for correct rendering, dispatching/redirecting, messages and access control handling
:param testcase: details of the form to test
"""
name, url = self._name_and_url((testcase["view"], testcase["kwargs"]))
form_name = testcase.get("form_name", "form")
expected_code = testcase.get("expected_code", 302)
......@@ -145,6 +197,9 @@ class BasicViewTests:
class ModelViewTests(BasicViewTests, TestCase):
"""
Basic view test cases for views from AKModel plus some custom tests
"""
fixtures = ['model.json']
ADMIN_MODELS = [
......@@ -172,35 +227,48 @@ class ModelViewTests(BasicViewTests, TestCase):
]
def test_admin(self):
"""
Test basic admin functionality (displaying and interacting with model instances)
"""
self.client.force_login(self.admin_user)
for model in self.ADMIN_MODELS:
# Special treatment for a subset of views (where we exchanged default functionality, e.g., create views)
if model[1] == "event":
view_name_with_prefix, url = self._name_and_url((f'admin:new_event_wizard_start', {}))
_, url = self._name_and_url(('admin:new_event_wizard_start', {}))
elif model[1] == "room":
view_name_with_prefix, url = self._name_and_url((f'admin:room-new', {}))
_, url = self._name_and_url(('admin:room-new', {}))
# Otherwise, just call the creation form view
else:
view_name_with_prefix, url = self._name_and_url((f'admin:AKModel_{model[1]}_add', {}))
_, url = self._name_and_url((f'admin:AKModel_{model[1]}_add', {}))
response = self.client.get(url)
self.assertEqual(response.status_code, 200, msg=f"Add form for model {model[1]} ({url}) broken")
for model in self.ADMIN_MODELS:
# Test the update view using the first existing instance of each model
m = model[0].objects.first()
if m is not None:
view_name_with_prefix, url = self._name_and_url((f'admin:AKModel_{model[1]}_change', {'object_id': m.pk}))
_, url = self._name_and_url(
(f'admin:AKModel_{model[1]}_change', {'object_id': m.pk})
)
response = self.client.get(url)
self.assertEqual(response.status_code, 200, msg=f"Edit form for model {model[1]} ({url}) broken")
def test_wiki_export(self):
"""
Test wiki export
This will test whether the view renders at all and whether the export list contains the correct AKs
"""
self.client.force_login(self.admin_user)
export_url = reverse_lazy(f"admin:ak_wiki_export", kwargs={'slug': 'kif42'})
export_url = reverse_lazy("admin:ak_wiki_export", kwargs={'slug': 'kif42'})
response = self.client.get(export_url)
self.assertEqual(response.status_code, 200, "Export not working at all")
export_count = 0
for category, aks in response.context["categories_with_aks"]:
for _, aks in response.context["categories_with_aks"]:
for ak in aks:
self.assertEqual(ak.include_in_export, True, f"AK with export flag set to False (pk={ak.pk}) included in export")
self.assertEqual(ak.include_in_export, True,
f"AK with export flag set to False (pk={ak.pk}) included in export")
self.assertNotEqual(ak.pk, 1, "AK known to be excluded from export (PK 1) included in export")
export_count += 1
......