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 4310 additions and 0 deletions
import zoneinfo
from django.apps import apps
from django.test import override_settings, TestCase
from django.urls import reverse
from django.utils.timezone import now
from AKDashboard.models import DashboardButton
from AKModel.models import AK, AKCategory, Event
from AKModel.tests import BasicViewTests
class DashboardTests(TestCase):
"""
Specific Dashboard Tests
"""
@classmethod
def setUpTestData(cls):
"""
Initialize Test database
"""
super().setUpTestData()
cls.event = Event.objects.create(
name="Dashboard Test Event",
slug="dashboardtest",
timezone=zoneinfo.ZoneInfo("Europe/Berlin"),
start=now(),
end=now(),
active=True,
plan_hidden=False,
)
cls.default_category = AKCategory.objects.create(
name="Test Category",
event=cls.event,
)
def test_dashboard_view(self):
"""
Check that the main dashboard is reachable
(would also be covered by generic view testcase below)
"""
url = reverse('dashboard:dashboard_event', kwargs={"slug": self.event.slug})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_nonexistent_dashboard_view(self):
"""
Make sure there is no dashboard for an non-existing event
"""
url = reverse('dashboard:dashboard_event', kwargs={"slug": "nonexistent-event"})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
@override_settings(DASHBOARD_SHOW_RECENT=True)
def test_history(self):
"""
Test displaying of history
For the sake of that test, the setting to show recent events in dashboard is enforced to be true
regardless of the default configuration currently in place
"""
url = reverse('dashboard:dashboard_event', kwargs={"slug": self.event.slug})
# History should be empty
response = self.client.get(url)
self.assertQuerySetEqual(response.context["recent_changes"], [])
AK.objects.create(
name="Test AK",
category=self.default_category,
event=self.event,
)
# History should now contain one AK (Test AK)
response = self.client.get(url)
self.assertEqual(len(response.context["recent_changes"]), 1)
self.assertEqual(response.context["recent_changes"][0]['text'], "New AK: Test AK.")
def test_public(self):
"""
Test handling of public and private events
(only public events should be part of the standard dashboard,
but there should be an individual dashboard for both public and private events)
"""
url_dashboard_index = reverse('dashboard:dashboard')
url_event_dashboard = reverse('dashboard:dashboard_event', kwargs={"slug": self.event.slug})
# Non-Public event (should not be part of the global dashboard
# but should have an individual dashboard page for those knowing the url)
self.event.public = False
self.event.save()
response = self.client.get(url_dashboard_index)
self.assertEqual(response.status_code, 200)
self.assertFalse(self.event in response.context["active_and_current_events"])
self.assertFalse(self.event in response.context["old_events"])
response = self.client.get(url_event_dashboard)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context["event"], self.event)
# Public event -- should be part of the global dashboard
self.event.public = True
self.event.save()
response = self.client.get(url_dashboard_index)
self.assertEqual(response.status_code, 200)
self.assertTrue(self.event in response.context["active_and_current_events"])
def test_active(self):
"""
Test existence of buttons with regard to activity status of the given event
"""
url_event_dashboard = reverse('dashboard:dashboard_event', kwargs={"slug": self.event.slug})
if apps.is_installed('AKSubmission'):
# Non-active event -> No submission
self.event.active = False
self.event.save()
response = self.client.get(url_event_dashboard)
self.assertNotContains(response, "AK Submission")
# Active event -> Submission should be open
self.event.active = True
self.event.save()
response = self.client.get(url_event_dashboard)
self.assertContains(response, "AK Submission")
def test_plan_hidden(self):
"""
Test visibility of plan buttons with regard to plan visibility status for a given event
"""
url_event_dashboard = reverse('dashboard:dashboard_event', kwargs={"slug": self.event.slug})
if apps.is_installed('AKPlan'):
# Plan hidden? No buttons should show up
self.event.plan_hidden = True
self.event.save()
response = self.client.get(url_event_dashboard)
self.assertNotContains(response, "Current AKs")
self.assertNotContains(response, "AK Wall")
# Plan not hidden?
# Buttons for current AKs and AK Wall should be on the page
self.event.plan_hidden = False
self.event.save()
response = self.client.get(url_event_dashboard)
self.assertContains(response, "Current AKs")
self.assertContains(response, "AK Wall")
def test_dashboard_buttons(self):
"""
Make sure manually added buttons are displayed correctly
"""
url_event_dashboard = reverse('dashboard:dashboard_event', kwargs={"slug": self.event.slug})
response = self.client.get(url_event_dashboard)
self.assertNotContains(response, "Dashboard Button Test")
DashboardButton.objects.create(
text="Dashboard Button Test",
event=self.event
)
response = self.client.get(url_event_dashboard)
self.assertContains(response, "Dashboard Button Test")
class DashboardViewTests(BasicViewTests, TestCase):
"""
Generic view tests, based on :class:`AKModel.BasicViewTests` as specified in this class in VIEWS
"""
fixtures = ['model.json', 'dashboard.json']
APP_NAME = 'dashboard'
VIEWS = [
('dashboard', {}),
('dashboard_event', {'slug': 'kif42'}),
]
from django.urls import path
from AKDashboard import views
app_name = "dashboard"
urlpatterns = [
path('', views.DashboardView.as_view(), name="dashboard"),
path('<slug:slug>/', views.DashboardEventView.as_view(), name='dashboard_event'),
]
from django.apps import apps
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic import TemplateView, DetailView
from django.utils.translation import gettext_lazy as _
from AKModel.models import Event, AK, AKSlot
from AKPlanning import settings
class DashboardView(TemplateView):
"""
Index view of dashboard and therefore the main entry point for AKPlanning
Displays information and buttons for all public events
"""
template_name = 'AKDashboard/dashboard.html'
@method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Load events and split between active and current/featured events and those that should show smaller below
context["active_and_current_events"] = []
context["old_events"] = []
events = Event.objects.filter(public=True).order_by("-active", "-pk").prefetch_related('dashboardbutton_set')
for event in events:
if event.active or len(context["active_and_current_events"]) < settings.DASHBOARD_MAX_FEATURED_EVENTS:
context["active_and_current_events"].append(event)
else:
context["old_events"].append(event)
context["active_event_count"] = len(context["active_and_current_events"])
context["old_event_count"] = len(context["old_events"])
context["total_event_count"] = context["active_event_count"] + context["old_event_count"]
return context
class DashboardEventView(DetailView):
"""
Dashboard view for a single event
In addition to the basic information and the buttons,
an overview over recent events (new and changed AKs, moved AKSlots) for the given event is shown.
The event dashboard also exists for non-public events (one only needs to know the URL/slug of the event).
"""
template_name = 'AKDashboard/dashboard_event.html'
context_object_name = 'event'
model = Event
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Show feed of recent changes (if activated)
if settings.DASHBOARD_SHOW_RECENT:
# Create a list of chronically sorted events (both AK and plan changes):
recent_changes = []
# Newest AKs (if AKSubmission is used)
if apps.is_installed("AKSubmission"):
# Get the latest x changes (if there are that many),
# where x corresponds to the entry threshold configured in the settings
# (such that the list will be completely filled even if there are no (newer) plan changes)
submission_changes = AK.history.filter(event=context['event'])[:int(settings.DASHBOARD_RECENT_MAX)] # pylint: disable=no-member, line-too-long
# Create textual representation including icons
for s in submission_changes:
if s.history_type == '+':
text = _('New AK: %(ak)s.') % {'ak': s.name}
icon = ('plus-square', 'far')
elif s.history_type == '~':
text = _('AK "%(ak)s" edited.') % {'ak': s.name}
icon = ('pen-square', 'fas')
else:
text = _('AK "%(ak)s" deleted.') % {'ak': s.name}
icon = ('times', 'fas')
# Store representation in change list (still unsorted)
recent_changes.append(
{'icon': icon, 'text': text, 'link': s.instance.detail_url, 'timestamp': s.history_date}
)
# Changes in plan (if AKPlan is used and plan is publicly visible)
if apps.is_installed("AKPlan") and not context['event'].plan_hidden:
# Get the latest plan changes (again using a threshold, see above)
last_changed_slots = AKSlot.objects.select_related('ak').filter(event=context['event'], start__isnull=False).order_by('-updated')[:int(settings.DASHBOARD_RECENT_MAX)] #pylint: disable=line-too-long
for changed_slot in last_changed_slots:
# Create textual representation including icons and links and store in list (still unsorted)
recent_changes.append({'icon': ('clock', 'far'),
'text': _('AK "%(ak)s" (re-)scheduled.') % {'ak': changed_slot.ak.name},
'link': changed_slot.ak.detail_url,
'timestamp': changed_slot.updated})
# Sort by change date...
recent_changes.sort(key=lambda x: x['timestamp'], reverse=True)
# ... and restrict to the latest 25 changes
context['recent_changes'] = recent_changes[:int(settings.DASHBOARD_RECENT_MAX)]
else:
context['recent_changes'] = []
return context
This diff is collapsed.
from django.apps import AppConfig
from django.contrib.admin.apps import AdminConfig
class AkmodelConfig(AppConfig):
"""
App configuration (default, only specifies name of the app)
"""
name = 'AKModel'
class AKAdminConfig(AdminConfig):
"""
App configuration for admin
Loading a custom version here allows to add additional contex and further adapt the behavior of the admin interface
"""
default_site = 'AKModel.site.AKAdminSite'
# This part of the code was adapted from pretalx (https://github.com/pretalx/pretalx)
# Copyright 2017-2019, Tobias Kunze
# Original Copyrights licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
# Documentation was mainly added by us, other changes are marked in the code
import datetime
import json
from django import forms
from django.db import transaction
from django.db.models.signals import post_save
from django.utils.dateparse import parse_datetime
from django.utils.translation import gettext_lazy as _
from AKModel.availability.models import Availability
from AKModel.availability.serializers import AvailabilitySerializer
from AKModel.models import Event
class AvailabilitiesFormMixin(forms.Form):
"""
Mixin for forms to add availabilities functionality to it
Will handle the rendering and population of an availabilities field
"""
availabilities = forms.CharField(
label=_('Availability'),
help_text=_(
'Click and drag to mark the availability during the event, double-click to delete. '
'Or use the start and end inputs to add entries to the calendar view.' # Adapted help text
),
widget=forms.TextInput(attrs={'class': 'availabilities-editor-data'}),
required=False,
)
def _serialize(self, event, instance):
"""
Serialize relevant availabilities into a JSON format to populate the text field in the form
:param event: event the availabilities belong to (relevant for start and end times)
:param instance: the entity availabilities in this form should belong to (e.g., an AK, or a Room)
:return: JSON serializiation of the relevant availabilities
:rtype: str
"""
if instance:
availabilities = AvailabilitySerializer(
instance.availabilities.all(), many=True
).data
else:
availabilities = []
return json.dumps(
{
'availabilities': availabilities,
'event': {
# 'timezone': event.timezone,
'date_from': str(event.start),
'date_to': str(event.end),
},
}
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Load event information and populate availabilities text field
self.event = self.initial.get('event')
if isinstance(self.event, int):
self.event = Event.objects.get(pk=self.event)
initial = kwargs.pop('initial', {})
initial['availabilities'] = self._serialize(self.event, kwargs['instance'])
if not isinstance(self, forms.BaseModelForm):
kwargs.pop('instance')
kwargs['initial'] = initial
def _parse_availabilities_json(self, jsonavailabilities):
"""
Turn raw JSON availabilities into a list of model instances
:param jsonavailabilities: raw json input
:return: a list of availability objects corresponding to the raw input
:rtype: List[Availability]
"""
try:
rawdata = json.loads(jsonavailabilities)
except ValueError as exc:
raise forms.ValidationError("Submitted availabilities are not valid json.") from exc
if not isinstance(rawdata, dict):
raise forms.ValidationError(
"Submitted json does not comply with expected format, should be object."
)
availabilities = rawdata.get('availabilities')
if not isinstance(availabilities, list):
raise forms.ValidationError(
"Submitted json does not comply with expected format, missing or malformed availabilities field"
)
return availabilities
def _parse_datetime(self, strdate):
"""
Parse input date string
This will try to correct timezone information if needed
:param strdate: string representing a timestamp
:return: a timestamp object
"""
tz = self.event.timezone # adapt to our event model
obj = parse_datetime(strdate)
if not obj:
raise TypeError
if obj.tzinfo is None:
# Adapt to new python timezone interface
obj = obj.replace(tzinfo=tz)
return obj
def _validate_availability(self, rawavail):
"""
Validate a raw availability instance input by making sure the relevant fields are present and can be parsed
The cleaned up values that are produced to test the validity of the input are stored in-place in the input
object for later usage in cleaning/parsing to availability objects
:param rawavail: object to validate/clean
"""
message = _("The submitted availability does not comply with the required format.")
if not isinstance(rawavail, dict):
raise forms.ValidationError(message)
rawavail.pop('id', None)
rawavail.pop('allDay', None)
if not set(rawavail.keys()) == {'start', 'end'}:
raise forms.ValidationError(message)
try:
rawavail['start'] = self._parse_datetime(rawavail['start'])
rawavail['end'] = self._parse_datetime(rawavail['end'])
# Adapt: Better error handling
except (TypeError, ValueError) as exc:
raise forms.ValidationError(
_("The submitted availability contains an invalid date.")
) from exc
timeframe_start = self.event.start # adapt to our event model
if rawavail['start'] < timeframe_start:
rawavail['start'] = timeframe_start
# add 1 day, not 24 hours, https://stackoverflow.com/a/25427822/2486196
timeframe_end = self.event.end # adapt to our event model
timeframe_end = timeframe_end + datetime.timedelta(days=1)
if rawavail['end'] > timeframe_end:
# If the submitted availability ended outside the event timeframe, fix it silently
rawavail['end'] = timeframe_end
def clean_availabilities(self):
"""
Turn raw availabilities into real availability objects
:return:
"""
data = self.cleaned_data.get('availabilities')
required = (
'availabilities' in self.fields and self.fields['availabilities'].required
)
if not data:
if required:
raise forms.ValidationError(_('Please fill in your availabilities!'))
return None
rawavailabilities = self._parse_availabilities_json(data)
availabilities = []
for rawavail in rawavailabilities:
self._validate_availability(rawavail)
availabilities.append(Availability(event_id=self.event.id, **rawavail))
if not availabilities and required:
raise forms.ValidationError(_('Please fill in your availabilities!'))
return availabilities
def _set_foreignkeys(self, instance, availabilities):
"""
Set the reference to `instance` in each given availability.
For example, set the availabilitiy.room_id to instance.id, in
case instance of type Room.
"""
reference_name = instance.availabilities.field.name + '_id'
for avail in availabilities:
setattr(avail, reference_name, instance.id)
def _replace_availabilities(self, instance, availabilities: [Availability]):
"""
Replace the existing list of availabilities belonging to an entity with a new, updated one
This will trigger a post_save signal for usage in constraint violation checking
:param instance: entity the availabilities belong to
:param availabilities: list of new availabilities
"""
with transaction.atomic():
# TODO: do not recreate objects unnecessarily, give the client the IDs, so we can track modifications and
# leave unchanged objects alone
instance.availabilities.all().delete()
Availability.objects.bulk_create(availabilities)
# Adaption:
# Trigger post save signal manually to make sure constraints are updated accordingly
# Doing this one time is sufficient, since this will nevertheless update all availability constraint
# violations of the corresponding AK
if len(availabilities) > 0:
post_save.send(Availability, instance=availabilities[0], created=True)
def save(self, *args, **kwargs):
"""
Override the saving method of the (model) form
"""
instance = super().save(*args, **kwargs)
availabilities = self.cleaned_data.get('availabilities')
if availabilities is not None:
self._set_foreignkeys(instance, availabilities)
self._replace_availabilities(instance, availabilities)
return instance # adapt to our forms
# This part of the code was adapted from pretalx (https://github.com/pretalx/pretalx)
# Copyright 2017-2019, Tobias Kunze
# Original Copyrights licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
# Changes are marked in the code
import datetime
from typing import List
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from AKModel.models import Event, AKOwner, Room, AK, AKCategory
zero_time = datetime.time(0, 0)
# CHANGES:
# ScopeManager and LogMixin removed as they are not used in this project
# adapted to event, people and room models
# remove serialization as requirements are not covered
# add translation
# add meta class
# enable availabilities for AKs and AKCategories
# add verbose names and help texts to model attributes
# adapt or extemd documentation
class Availability(models.Model):
"""The Availability class models when people or rooms are available for.
The power of this class is not within its rather simple data model,
but with the operations available on it. An availability object can
span multiple days, but due to our choice of input widget, it will
usually only span a single day at most.
"""
# pylint: disable=broad-exception-raised
event = models.ForeignKey(
to=Event,
related_name='availabilities',
on_delete=models.CASCADE,
verbose_name=_('Event'),
help_text=_('Associated event'),
)
person = models.ForeignKey(
to=AKOwner,
related_name='availabilities',
on_delete=models.CASCADE,
null=True,
blank=True,
verbose_name=_('Person'),
help_text=_('Person whose availability this is'),
)
room = models.ForeignKey(
to=Room,
related_name='availabilities',
on_delete=models.CASCADE,
null=True,
blank=True,
verbose_name=_('Room'),
help_text=_('Room whose availability this is'),
)
ak = models.ForeignKey(
to=AK,
related_name='availabilities',
on_delete=models.CASCADE,
null=True,
blank=True,
verbose_name=_('AK'),
help_text=_('AK whose availability this is'),
)
ak_category = models.ForeignKey(
to=AKCategory,
related_name='availabilities',
on_delete=models.CASCADE,
null=True,
blank=True,
verbose_name=_('AK Category'),
help_text=_('AK Category whose availability this is'),
)
start = models.DateTimeField()
end = models.DateTimeField()
def __str__(self) -> str:
person = self.person.name if self.person else None
room = getattr(self.room, 'name', None)
event = getattr(getattr(self, 'event', None), 'name', None)
ak = getattr(self.ak, 'name', None)
ak_category = getattr(self.ak_category, 'name', None)
return f'Availability(event={event}, person={person}, room={room}, ak={ak}, ak category={ak_category})'
def __hash__(self):
return hash(
(getattr(self, 'event', None), self.person, self.room, self.ak, self.ak_category, self.start, self.end))
def __eq__(self, other: 'Availability') -> bool:
"""Comparisons like ``availability1 == availability2``.
Checks if ``event``, ``person``, ``room``, ``ak``, ``ak_category``, ``start`` and ``end``
are the same.
"""
return all(
(
getattr(self, attribute, None) == getattr(other, attribute, None)
for attribute in ['event', 'person', 'room', 'ak', 'ak_category', 'start', 'end']
)
)
@cached_property
def all_day(self) -> bool:
"""Checks if the Availability spans one (or, technically: multiple)
complete day."""
return self.start.time() == zero_time and self.end.time() == zero_time
def overlaps(self, other: 'Availability', strict: bool) -> bool:
"""Test if two Availabilities overlap.
:param other:
:param strict: Only count a real overlap as overlap, not direct adjacency.
"""
if not isinstance(other, Availability):
raise Exception('Please provide an Availability object')
if strict:
return (
(self.start <= other.start < self.end)
or (self.start < other.end <= self.end)
or (other.start <= self.start < other.end)
or (other.start < self.end <= other.end)
)
return (
(self.start <= other.start <= self.end)
or (self.start <= other.end <= self.end)
or (other.start <= self.start <= other.end)
or (other.start <= self.end <= other.end)
)
def contains(self, other: 'Availability') -> bool:
"""Tests if this availability starts before and ends after the
other."""
return self.start <= other.start and self.end >= other.end
def merge_with(self, other: 'Availability') -> 'Availability':
"""Return a new Availability which spans the range of this one and the
given one."""
if not isinstance(other, Availability):
raise Exception('Please provide an Availability object.')
if not other.overlaps(self, strict=False):
raise Exception('Only overlapping Availabilities can be merged.')
return Availability(
start=min(self.start, other.start), end=max(self.end, other.end)
)
def __or__(self, other: 'Availability') -> 'Availability':
"""Performs the merge operation: ``availability1 | availability2``"""
return self.merge_with(other)
def intersect_with(self, other: 'Availability') -> 'Availability':
"""Return a new Availability which spans the range covered both by this
one and the given one."""
if not isinstance(other, Availability):
raise Exception('Please provide an Availability object.')
if not other.overlaps(self, False):
raise Exception('Only overlapping Availabilities can be intersected.')
return Availability(
start=max(self.start, other.start), end=min(self.end, other.end)
)
def __and__(self, other: 'Availability') -> 'Availability':
"""Performs the intersect operation: ``availability1 &
availability2``"""
return self.intersect_with(other)
@classmethod
def union(cls, availabilities: List['Availability']) -> List['Availability']:
"""Return the minimal list of Availability objects which are covered by
at least one given Availability."""
if not availabilities:
return []
availabilities = sorted(availabilities, key=lambda a: a.start)
result = [availabilities[0]]
availabilities = availabilities[1:]
for avail in availabilities:
if avail.overlaps(result[-1], False):
result[-1] = result[-1].merge_with(avail)
else:
result.append(avail)
return result
@classmethod
def _pair_intersection(
cls,
availabilities_a: List['Availability'],
availabilities_b: List['Availability'],
) -> List['Availability']:
"""return the list of Availabilities, which are covered by each of the
given sets."""
result = []
# yay for O(b*a) time! I am sure there is some fancy trick to make this faster,
# but we're dealing with less than 100 items in total, sooo.. ¯\_(ツ)_/¯
for a in availabilities_a:
for b in availabilities_b:
if a.overlaps(b, True):
result.append(a.intersect_with(b))
return result
@classmethod
def intersection(
cls, *availabilitysets: List['Availability']
) -> List['Availability']:
"""Return the list of Availabilities which are covered by all of the
given sets."""
# get rid of any overlaps and unmerged ranges in each set
availabilitysets = [cls.union(avialset) for avialset in availabilitysets]
# bail out for obvious cases (there are no sets given, one of the sets is empty)
if not availabilitysets:
return []
if not all(availabilitysets):
return []
# start with the very first set ...
result = availabilitysets[0]
for availset in availabilitysets[1:]:
# ... subtract each of the other sets
result = cls._pair_intersection(result, availset)
return result
@property
def simplified(self):
"""
Get a simplified (only Weekday, hour and minute) string representation of an availability
:return: simplified string version
:rtype: str
"""
return (f'{self.start.astimezone(self.event.timezone).strftime("%a %H:%M")}-'
f'{self.end.astimezone(self.event.timezone).strftime("%a %H:%M")}')
@classmethod
def with_event_length(cls, event, person=None, room=None, ak=None, ak_category=None):
"""
Create an availability covering exactly the time between event start and event end.
Can e.g., be used to create default availabilities.
:param event: relevant event
:param person: person, if availability should be connected to a person
:param room: room, if availability should be connected to a room
:param ak: ak, if availability should be connected to a ak
:param ak_category: ak_category, if availability should be connected to a ak_category
:return: availability associated to the entity oder entities selected
:rtype: Availability
"""
timeframe_start = event.start # adapt to our event model
# add 1 day, not 24 hours, https://stackoverflow.com/a/25427822/2486196
timeframe_end = event.end # adapt to our event model
timeframe_end = timeframe_end + datetime.timedelta(days=1)
return Availability(start=timeframe_start, end=timeframe_end, event=event, person=person,
room=room, ak=ak, ak_category=ak_category)
class Meta:
verbose_name = _('Availability')
verbose_name_plural = _('Availabilities')
ordering = ['event', 'start']
# This part of the code was adapted from pretalx (https://github.com/pretalx/pretalx)
# Copyright 2017-2019, Tobias Kunze
# Original Copyrights licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
# Documentation was mainly added by us, other changes are marked in the code
from django.utils import timezone
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer
from AKModel.availability.models import Availability
class AvailabilitySerializer(ModelSerializer):
"""
REST Framework Serializer for Availability
"""
allDay = SerializerMethodField()
start = SerializerMethodField()
end = SerializerMethodField()
def get_allDay(self, obj): # pylint: disable=invalid-name
"""
Bridge between naming conventions of python and fullcalendar by providing the all_day field as allDay, too
"""
return obj.all_day
def get_start(self, obj):
"""
Get start timestamp
Use already localized strings in serialized field
(default would be UTC, but that would require heavy timezone calculation on client side)
"""
return timezone.localtime(obj.start, obj.event.timezone).strftime("%Y-%m-%dT%H:%M:%S")
def get_end(self, obj):
"""
Get end timestamp
Use already localized strings in serialized field
(default would be UTC, but that would require heavy timezone calculation on client side)
"""
return timezone.localtime(obj.end, obj.event.timezone).strftime("%Y-%m-%dT%H:%M:%S")
class Meta:
model = Availability
fields = ('id', 'start', 'end', 'allDay')
"""
Environment definitions
Needed for tex compilation
"""
import re
from django_tex.environment import environment
# Used to filter all very special UTF-8 chars that are probably not contained in the LaTeX fonts
# and would hence cause compilation errors
utf8_replace_pattern = re.compile('[^\u0000-\u206F]', re.UNICODE)
def latex_escape_utf8(value):
"""
Escape latex special chars and remove invalid utf-8 values
:param value: string to escape
:type value: str
:return: escaped string
:rtype: str
"""
return (utf8_replace_pattern.sub('', value).replace('&', r'\&').replace('_', r'\_').replace('#', r'\#').
replace('$', r'\$').replace('%', r'\%').replace('{', r'\{').replace('}', r'\}'))
def improved_tex_environment(**options):
"""
Encapsulate our improved latex environment for usage
"""
env = environment(**options)
env.filters.update({
'latex_escape_utf8': latex_escape_utf8,
})
return env
[
{
"model": "AKModel.event",
"pk": 1,
"fields": {
"name": "KIF 23",
"slug": "kif23",
"place": "Neuland",
"timezone": "Europe/Berlin",
"start": "2020-10-01T17:41:22Z",
"end": "2020-10-04T17:41:30Z",
"reso_deadline": "2020-10-03T10:00:00Z",
"interest_start": null,
"interest_end": null,
"public": true,
"active": false,
"plan_hidden": true,
"plan_published_at": null,
"base_url": "",
"wiki_export_template_name": "",
"default_slot": "2.00",
"contact_email": "dummy@eyample.org"
}
},
{
"model": "AKModel.event",
"pk": 2,
"fields": {
"name": "KIF 42",
"slug": "kif42",
"place": "Neuland noch neuer",
"timezone": "Europe/Berlin",
"start": "2020-11-06T17:51:26Z",
"end": "2020-11-10T17:51:27Z",
"reso_deadline": "2020-11-08T17:51:42Z",
"interest_start": null,
"interest_end": null,
"public": true,
"active": true,
"plan_hidden": false,
"plan_published_at": "2022-12-01T21:50:01Z",
"base_url": "",
"wiki_export_template_name": "",
"default_slot": "2.00",
"contact_email": "dummy@example.org"
}
},
{
"model": "AKModel.akowner",
"pk": 1,
"fields": {
"name": "a",
"slug": "a",
"institution": "Uni X",
"link": "",
"event": 2
}
},
{
"model": "AKModel.akowner",
"pk": 2,
"fields": {
"name": "b",
"slug": "b",
"institution": "Hochschule Y",
"link": "",
"event": 2
}
},
{
"model": "AKModel.akowner",
"pk": 3,
"fields": {
"name": "c",
"slug": "c",
"institution": "",
"link": "",
"event": 1
}
},
{
"model": "AKModel.akowner",
"pk": 4,
"fields": {
"name": "d",
"slug": "d",
"institution": "",
"link": "",
"event": 1
}
},
{
"model": "AKModel.akcategory",
"pk": 1,
"fields": {
"name": "Spa▀",
"color": "275246",
"description": "",
"present_by_default": true,
"event": 1
}
},
{
"model": "AKModel.akcategory",
"pk": 2,
"fields": {
"name": "Ernst",
"color": "234567",
"description": "",
"present_by_default": true,
"event": 1
}
},
{
"model": "AKModel.akcategory",
"pk": 3,
"fields": {
"name": "Spa▀/Kultur",
"color": "333333",
"description": "",
"present_by_default": true,
"event": 2
}
},
{
"model": "AKModel.akcategory",
"pk": 4,
"fields": {
"name": "Inhalt",
"color": "456789",
"description": "",
"present_by_default": true,
"event": 2
}
},
{
"model": "AKModel.akcategory",
"pk": 5,
"fields": {
"name": "Meta",
"color": "111111",
"description": "",
"present_by_default": true,
"event": 2
}
},
{
"model": "AKModel.aktrack",
"pk": 1,
"fields": {
"name": "Track 1",
"color": "",
"event": 2
}
},
{
"model": "AKModel.akrequirement",
"pk": 1,
"fields": {
"name": "Beamer",
"event": 1
}
},
{
"model": "AKModel.akrequirement",
"pk": 2,
"fields": {
"name": "Internet",
"event": 1
}
},
{
"model": "AKModel.akrequirement",
"pk": 3,
"fields": {
"name": "BBB",
"event": 2
}
},
{
"model": "AKModel.akrequirement",
"pk": 4,
"fields": {
"name": "Mumble",
"event": 2
}
},
{
"model": "AKModel.akrequirement",
"pk": 5,
"fields": {
"name": "Matrix",
"event": 2
}
},
{
"model": "AKModel.aktype",
"pk": 1,
"fields": {
"name": "Input",
"event": 2
}
},
{
"model": "AKModel.historicalak",
"pk": 1,
"fields": {
"id": 1,
"name": "Test AK Inhalt",
"short_name": "test1",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": true,
"notes": "",
"category": 4,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:28:59.265Z",
"history_change_reason": null,
"history_type": "+",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 2,
"fields": {
"id": 1,
"name": "Test AK Inhalt",
"short_name": "test1",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": true,
"notes": "",
"category": 4,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:28:59.305Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 3,
"fields": {
"id": 2,
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "",
"category": 5,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:29:40.296Z",
"history_change_reason": null,
"history_type": "+",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 4,
"fields": {
"id": 2,
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "",
"category": 5,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:29:40.355Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 5,
"fields": {
"id": 3,
"name": "AK Wish",
"short_name": "wish1",
"description": "Description of my Wish",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"category": 3,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:30:59.469Z",
"history_change_reason": null,
"history_type": "+",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 6,
"fields": {
"id": 3,
"name": "AK Wish",
"short_name": "wish1",
"description": "Description of my Wish",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"category": 3,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:30:59.509Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 7,
"fields": {
"id": 2,
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "",
"category": 5,
"track": 1,
"event": 2,
"history_date": "2022-12-02T12:27:14.277Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.ak",
"pk": 1,
"fields": {
"name": "Test AK Inhalt",
"short_name": "test1",
"description": "",
"link": "",
"protocol_link": "",
"category": 4,
"track": null,
"reso": false,
"present": true,
"notes": "",
"interest": -1,
"interest_counter": 0,
"include_in_export": false,
"event": 2,
"owners": [
1
],
"requirements": [
3
],
"conflicts": [],
"prerequisites": []
}
},
{
"model": "AKModel.ak",
"pk": 2,
"fields": {
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"category": 5,
"track": 1,
"reso": false,
"present": null,
"notes": "",
"interest": -1,
"interest_counter": 0,
"event": 2,
"owners": [
2
],
"requirements": [],
"conflicts": [],
"prerequisites": []
}
},
{
"model": "AKModel.ak",
"pk": 3,
"fields": {
"name": "AK Wish",
"short_name": "wish1",
"description": "Description of my Wish",
"link": "",
"protocol_link": "",
"category": 3,
"track": null,
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"interest": -1,
"interest_counter": 0,
"event": 2,
"owners": [],
"requirements": [
4
],
"conflicts": [
1
],
"prerequisites": [
2
]
}
},
{
"model": "AKModel.room",
"pk": 1,
"fields": {
"name": "Testraum",
"location": "BBB",
"capacity": -1,
"event": 2,
"properties": [
3
]
}
},
{
"model": "AKModel.room",
"pk": 2,
"fields": {
"name": "Testraum 2",
"location": "",
"capacity": 30,
"event": 2,
"properties": []
}
},
{
"model": "AKModel.akslot",
"pk": 1,
"fields": {
"ak": 1,
"room": 2,
"start": "2020-11-06T18:30:00Z",
"duration": "2.00",
"fixed": false,
"event": 2,
"updated": "2022-12-02T12:23:11.856Z"
}
},
{
"model": "AKModel.akslot",
"pk": 2,
"fields": {
"ak": 2,
"room": 1,
"start": "2020-11-08T12:30:00Z",
"duration": "2.00",
"fixed": false,
"event": 2,
"updated": "2022-12-02T12:23:18.279Z"
}
},
{
"model": "AKModel.akslot",
"pk": 3,
"fields": {
"ak": 3,
"room": null,
"start": null,
"duration": "1.50",
"fixed": false,
"event": 2,
"updated": "2021-05-04T10:30:59.523Z"
}
},
{
"model": "AKModel.akslot",
"pk": 4,
"fields": {
"ak": 3,
"room": null,
"start": null,
"duration": "3.00",
"fixed": false,
"event": 2,
"updated": "2021-05-04T10:30:59.528Z"
}
},
{
"model": "AKModel.akslot",
"pk": 5,
"fields": {
"ak": 1,
"room": null,
"start": null,
"duration": "2.00",
"fixed": false,
"event": 2,
"updated": "2022-12-02T12:23:11.856Z"
}
},
{
"model": "AKModel.constraintviolation",
"pk": 1,
"fields": {
"type": "soa",
"level": 10,
"event": 2,
"ak_owner": null,
"room": null,
"requirement": null,
"category": null,
"comment": "",
"timestamp": "2022-12-02T12:23:11.875Z",
"manually_resolved": false,
"aks": [
1
],
"ak_slots": [
1
]
}
},
{
"model": "AKModel.constraintviolation",
"pk": 2,
"fields": {
"type": "rng",
"level": 10,
"event": 2,
"ak_owner": null,
"room": 2,
"requirement": 3,
"category": null,
"comment": "",
"timestamp": "2022-12-02T12:23:11.890Z",
"manually_resolved": false,
"aks": [
1
],
"ak_slots": [
1
]
}
},
{
"model": "AKModel.constraintviolation",
"pk": 3,
"fields": {
"type": "soa",
"level": 10,
"event": 2,
"ak_owner": null,
"room": null,
"requirement": null,
"category": null,
"comment": "",
"timestamp": "2022-12-02T12:23:18.301Z",
"manually_resolved": false,
"aks": [
2
],
"ak_slots": [
2
]
}
},
{
"model": "AKModel.availability",
"pk": 1,
"fields": {
"event": 2,
"person": null,
"room": null,
"ak": 1,
"ak_category": null,
"start": "2020-11-07T08:00:00Z",
"end": "2020-11-07T18:00:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 2,
"fields": {
"event": 2,
"person": null,
"room": null,
"ak": 1,
"ak_category": null,
"start": "2020-11-09T10:00:00Z",
"end": "2020-11-09T16:30:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 3,
"fields": {
"event": 2,
"person": null,
"room": 1,
"ak": null,
"ak_category": null,
"start": "2020-11-06T17:51:26Z",
"end": "2020-11-10T23:00:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 4,
"fields": {
"event": 2,
"person": null,
"room": 2,
"ak": null,
"ak_category": null,
"start": "2020-11-06T17:51:26Z",
"end": "2020-11-06T21:00:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 5,
"fields": {
"event": 2,
"person": null,
"room": 2,
"ak": null,
"ak_category": null,
"start": "2020-11-08T15:30:00Z",
"end": "2020-11-08T19:30:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 6,
"fields": {
"event": 2,
"person": null,
"room": 2,
"ak": null,
"ak_category": null,
"start": "2020-11-07T18:30:00Z",
"end": "2020-11-07T21:30:00Z"
}
}
]
"""
Central and admin forms
"""
import csv
import io
from django import forms
from django.forms.utils import ErrorList
from django.utils.translation import gettext_lazy as _
from AKModel.availability.forms import AvailabilitiesFormMixin
from AKModel.models import Event, AKCategory, AKRequirement, Room, AKType
class DateTimeInput(forms.DateInput):
"""
Simple widget for datetime input fields using the HTML5 datetime-local input type
"""
input_type = 'datetime-local'
class NewEventWizardStartForm(forms.ModelForm):
"""
Initial view of new event wizard
This form is a model form for Event, but only with a subset of the required fields.
It is therefore not possible to really create an event using this form, but only to enter
information, in particular the timezone, that is needed to correctly handle/parse the user
inputs for further required fields like start and end of the event.
The form will be used for this partial input, the input of the remaining required fields
will then be handled by :class:`NewEventWizardSettingsForm` (see below).
"""
class Meta:
model = Event
fields = ['name', 'slug', 'timezone', 'plan_hidden']
widgets = {
'plan_hidden': forms.HiddenInput(),
}
# Special hidden field for wizard state handling
is_init = forms.BooleanField(initial=True, widget=forms.HiddenInput)
class NewEventWizardSettingsForm(forms.ModelForm):
"""
Form for second view of the event creation wizard.
Will handle the input of the remaining required as well as some optional fields.
See also :class:`NewEventWizardStartForm`.
"""
class Meta:
model = Event
fields = "__all__"
exclude = ['plan_published_at']
widgets = {
'name': forms.HiddenInput(),
'slug': forms.HiddenInput(),
'timezone': forms.HiddenInput(),
'active': forms.HiddenInput(),
'start': DateTimeInput(),
'end': DateTimeInput(),
'interest_start': DateTimeInput(),
'interest_end': DateTimeInput(),
'reso_deadline': DateTimeInput(),
'plan_hidden': forms.HiddenInput(),
}
class NewEventWizardPrepareImportForm(forms.Form):
"""
Wizard form for choosing an event to import/copy elements (requirements, categories, etc) from.
Is used to restrict the list of elements to choose from in the next step (see :class:`NewEventWizardImportForm`).
"""
import_event = forms.ModelChoiceField(
queryset=Event.objects.all(),
label=_("Copy ak requirements and ak categories of existing event"),
help_text=_("You can choose what to copy in the next step")
)
class NewEventWizardImportForm(forms.Form):
"""
Wizard form for excaclty choosing which elemments to copy/import for the newly created event.
Possible elements are categories, requirements, and dashboard buttons if AKDashboard is active.
The lists are restricted to elements from the event selected in the previous step
(see :class:`NewEventWizardPrepareImportForm`).
"""
import_categories = forms.ModelMultipleChoiceField(
queryset=AKCategory.objects.all(),
widget=forms.CheckboxSelectMultiple,
label=_("Copy ak categories"),
required=False,
)
import_requirements = forms.ModelMultipleChoiceField(
queryset=AKRequirement.objects.all(),
widget=forms.CheckboxSelectMultiple,
label=_("Copy ak requirements"),
required=False,
)
import_types = forms.ModelMultipleChoiceField(
queryset=AKType.objects.all(),
widget=forms.CheckboxSelectMultiple,
label=_("Copy types"),
required=False,
)
# pylint: disable=too-many-arguments
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None,
renderer=None):
super().__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, field_order,
use_required_attribute, renderer)
self.fields["import_categories"].queryset = self.fields["import_categories"].queryset.filter(
event=self.initial["import_event"])
self.fields["import_requirements"].queryset = self.fields["import_requirements"].queryset.filter(
event=self.initial["import_event"])
self.fields["import_types"].queryset = self.fields["import_types"].queryset.filter(
event=self.initial["import_event"])
# pylint: disable=import-outside-toplevel
# Local imports used to prevent cyclic imports and to only import when AKDashboard is available
from django.apps import apps
if apps.is_installed("AKDashboard"):
# If AKDashboard is active, allow to copy dashboard buttons, too
from AKDashboard.models import DashboardButton
self.fields["import_buttons"] = forms.ModelMultipleChoiceField(
queryset=DashboardButton.objects.filter(event=self.initial["import_event"]),
widget=forms.CheckboxSelectMultiple,
label=_("Copy dashboard buttons"),
required=False,
)
class NewEventWizardActivateForm(forms.ModelForm):
"""
Wizard form to activate the newly created event
"""
class Meta:
fields = ["active"]
model = Event
class AdminIntermediateForm(forms.Form):
"""
Base form for admin intermediate views (forms used there should inherit from this,
by default, the form is empty since it is only needed for the confirmation button)
"""
class AdminIntermediateActionForm(AdminIntermediateForm):
"""
Form for Admin Action Confirmation views -- has a pks field needed to handle the serialization/deserialization of
the IDs of the entities the user selected for the admin action to be performed on
"""
pks = forms.CharField(widget=forms.HiddenInput)
class SlideExportForm(AdminIntermediateForm):
"""
Form to control the slides generated from the AK list of an event
The user can select how many upcoming AKs are displayed at the footer to inform people that it is their turn soon,
whether the AK list should be restricted to those AKs that where marked for presentation, and whether ther should
be a symbol and empty space to take notes on for wishes
"""
num_next = forms.IntegerField(
min_value=0,
max_value=6,
initial=3,
label=_("# next AKs"),
help_text=_("How many next AKs should be shown on a slide?"))
presentation_mode = forms.TypedChoiceField(
initial=False,
label=_("Presentation only?"),
widget=forms.RadioSelect,
choices=((True, _('Yes')), (False, _('No'))),
coerce=lambda x: x == "True",
help_text=_("Restrict AKs to those that asked for chance to be presented?"))
wish_notes = forms.TypedChoiceField(
initial=False,
label=_("Space for notes in wishes?"),
widget=forms.RadioSelect,
choices=((True, _('Yes')), (False, _('No'))),
coerce=lambda x: x == "True",
help_text=_("Create symbols indicating space to note down owners and timeslots for wishes, e.g., to be filled "
"out on a touch screen while presenting?"))
class DefaultSlotEditorForm(AdminIntermediateForm):
"""
Form for default slot editor
"""
availabilities = forms.CharField(
label=_('Default Slots'),
help_text=_(
'Click and drag to add default slots, double-click to delete. '
'Or use the start and end inputs to add entries to the calendar view.'
),
widget=forms.TextInput(attrs={'class': 'availabilities-editor-data'}),
required=True,
)
class RoomBatchCreationForm(AdminIntermediateForm):
"""
Form for room batch creation
Allows to input a list of room details and choose whether default availabilities should be generated for these
rooms. Will check that the input follows a CSV format with at least a name column present.
"""
rooms = forms.CharField(
label=_('New rooms'),
help_text=_('Enter room details in CSV format. Required colum is "name", optional colums are "location", '
'"capacity", and "url" for online/hybrid rooms. Delimiter: Semicolon'),
widget=forms.Textarea,
required=True,
)
create_default_availabilities = forms.BooleanField(
label=_('Default availabilities?'),
help_text=_('Create default availabilities for all rooms?'),
required=False
)
def clean_rooms(self):
"""
Validate and transform the input for the rooms textfield
Treat the input as CSV and turn it into a dict containing the relevant information.
:return: a dict containing the raw room information
:rtype: dict[str, str]
"""
rooms_raw_text = self.cleaned_data["rooms"]
rooms_raw_dict = csv.DictReader(io.StringIO(rooms_raw_text), delimiter=";")
if "name" not in rooms_raw_dict.fieldnames:
raise forms.ValidationError(_("CSV must contain a name column"))
return rooms_raw_dict
class RoomForm(forms.ModelForm):
"""
Room (creation) form (basic), will be extended for handling of availabilities
(see :class:`RoomFormWithAvailabilities`) and also for creating hybrid rooms in AKOnline (if active)
"""
class Meta:
model = Room
fields = ['name',
'location',
'capacity',
'event',
]
class RoomFormWithAvailabilities(AvailabilitiesFormMixin, RoomForm):
"""
Room (update) form including handling of availabilities, extends :class:`RoomForm`
"""
class Meta:
model = Room
fields = ['name',
'location',
'capacity',
'properties',
'event',
]
widgets = {
'properties': forms.CheckboxSelectMultiple,
}
def __init__(self, *args, **kwargs):
# Init availability mixin
kwargs['initial'] = {}
super().__init__(*args, **kwargs)
self.initial = {**self.initial, **kwargs['initial']}
# Filter possible values for m2m when event is specified
if hasattr(self.instance, "event") and self.instance.event is not None:
self.fields["properties"].queryset = AKRequirement.objects.filter(event=self.instance.event)
This diff is collapsed.
import os
from django.core.management.commands.makemessages import Command as MakeMessagesCommand
class Command(MakeMessagesCommand):
"""
Adapted version of the :class:`MakeMessagesCommand`
Ensure PO files are generated using forward slashes in the location comments on all operating systems
"""
def find_files(self, root):
# Replace backward slashes with forward slashes if necessary in file list
all_files = super().find_files(root)
if os.sep != "\\":
return all_files
for file_entry in all_files:
if file_entry.dirpath == ".":
file_entry.dirpath = ""
elif file_entry.dirpath.startswith(".\\"):
file_entry.dirpath = file_entry.dirpath[2:].replace("\\", "/")
return all_files
def build_potfiles(self):
# Replace backward slashes with forward slashes if necessary in the files itself
pot_files = super().build_potfiles()
if os.sep != "\\":
return pot_files
for filename in pot_files:
with open(filename, "r", encoding="utf-8") as f:
lines = f.readlines()
fixed_lines = []
for line in lines:
if line.startswith("#: "):
line = line.replace("\\", "/")
fixed_lines.append(line)
with open(filename, "w", encoding="utf-8") as f:
f.writelines(fixed_lines)
return pot_files
from AKModel.metaviews.status import StatusManager
# create on instance of the :class:`AKModel.metaviews.status.StatusManager`
# that can then be accessed everywhere (singleton pattern)
status_manager = StatusManager()
from abc import ABC, abstractmethod
from django.contrib import admin, messages
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import FormView
from AKModel.forms import AdminIntermediateForm, AdminIntermediateActionForm
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
return context
class FilterByEventSlugMixin(EventSlugMixin):
"""
Mixin to filter different querysets based on a event slug from the request url
"""
def get_queryset(self):
"""
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))
if self.site_url != '':
extra["site_url"] = self.site_url
if self.title != '':
extra["title"] = self.title
return extra
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):
context = super().get_context_data(**kwargs)
context["title"] = self.title
context["preview"] = self.get_preview()
return context
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"] = [
_("Start"),
_("Settings"),
_("Event created, Prepare Import"),
_("Import categories & requirements"),
_("Activate?"),
_("Finish")
]
context["wizard_step_text"] = context["wizard_steps"][self.wizard_step - 1]
context["wizard_steps_total"] = len(context["wizard_steps"])
return context
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(","))
def get_initial(self):
initial = super().get_initial()
initial['pks'] = self.request.GET['pks']
return initial
def get_preview(self):
self.entities = self.get_queryset()
joined_entities = '\n'.join(str(e) for e in self.entities)
return f"{self.confirmation_message}:\n\n {joined_entities}"
def get_success_url(self):
return reverse(f"admin:{self.model._meta.app_label}_{self.model._meta.model_name}_changelist")
@abstractmethod
def action(self, form):
"""
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'])
self.action(form)
messages.add_message(self.request, messages.SUCCESS, self.success_message)
return super().form_valid(form)
class LoopActionMixin(ABC):
"""
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)
entity.save()
self.post_action()
@abstractmethod
def perform_action(self, entity):
"""
Action to perform on each entity
:param entity: entity to perform the action on
"""
def pre_action(self):
"""
Callback for custom action before loop starts
"""
def post_action(self):
"""
Callback for custom action after loop finished
"""
This diff is collapsed.