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
Select Git revision

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
Select Git revision
Show changes
Showing
with 1255 additions and 146 deletions
# Generated by Django 5.1.6 on 2025-05-11 15:21
from django.db import migrations, models
def create_slugs(apps, schema_editor):
"""
Automatically generate slugs from existing type names
"""
AKType = apps.get_model("AKModel", "AKType")
for ak_type in AKType.objects.all():
slug = ak_type.name.lower().split(" ")[0]
ak_type.slug = slug[:30] if len(slug) > 30 else slug
ak_type.save()
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0067_eventparticipant_requirements_and_more'),
]
operations = [
migrations.AddField(
model_name='aktype',
name='slug',
field=models.SlugField(max_length=30, null=True, verbose_name='Slug'),
),
migrations.RunPython(create_slugs, migrations.RunPython.noop),
migrations.AlterUniqueTogether(
name='aktype',
unique_together={('event', 'name')},
),
migrations.AlterField(
model_name='aktype',
name='slug',
field=models.SlugField(max_length=30, verbose_name='Slug'),
),
migrations.AlterUniqueTogether(
name='aktype',
unique_together={('event', 'name'), ('event', 'slug')},
),
]
# Generated by Django 5.2.1 on 2025-06-17 15:57
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0067_eventparticipant_requirements_and_more'),
('AKPreference', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='eventparticipant',
name='event',
),
migrations.RemoveField(
model_name='eventparticipant',
name='requirements',
),
migrations.RemoveField(
model_name='availability',
name='participant',
),
migrations.AddField(
model_name='event',
name='poll_hidden',
field=models.BooleanField(default=True, help_text='Hides preference poll for non-staff users', verbose_name='Poll Hidden'),
),
migrations.AddField(
model_name='event',
name='poll_published_at',
field=models.DateTimeField(blank=True, help_text='Timestamp at which the preference poll was published', null=True, verbose_name='Poll published at'),
),
migrations.DeleteModel(
name='AKPreference',
),
migrations.DeleteModel(
name='EventParticipant',
),
migrations.AddField(
model_name='availability',
name='participant',
field=models.ForeignKey(blank=True, help_text='Participant whose availability this is', null=True,
on_delete=django.db.models.deletion.CASCADE, related_name='availabilities',
to='AKPreference.eventparticipant', verbose_name='Participant'),
),
]
# Generated by Django 5.2.1 on 2025-06-17 18:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0068_aktype_slug'),
('AKModel', '0068_event_export_delete_preferences_participants'),
]
operations = [
]
# Generated by Django 5.2.3 on 2025-06-18 10:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0069_merge_20250617_1844'),
]
operations = [
migrations.AddField(
model_name='akrequirement',
name='relevant_for_participants',
field=models.BooleanField(default=False, help_text='Show this requirement when collecting participant preferences', verbose_name='Relevant for Participants?'),
),
]
import itertools import itertools
from datetime import timedelta import json
import math
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, Generator, Iterable
from django.db import models
from django.apps import apps from django.apps import apps
from django.conf import settings
from django.core.validators import RegexValidator
from django.db import models, transaction
from django.db.models import Count from django.db.models import Count
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.utils import timezone from django.utils import timezone
from django.utils.datetime_safe import datetime
from django.utils.text import slugify from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from simple_history.models import HistoricalRecords from simple_history.models import HistoricalRecords
from timezone_field import TimeZoneField 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'))
@dataclass
class OptimizerTimeslot:
"""Class describing a discrete timeslot. Used to interface with an optimizer."""
avail: "Availability"
"""The availability object corresponding to this timeslot."""
idx: int
"""The unique index of this optimizer timeslot."""
constraints: set[str]
"""The set of time constraints fulfilled by this object."""
def merge(self, other: "OptimizerTimeslot") -> "OptimizerTimeslot":
"""Merge with other OptimizerTimeslot.
Creates a new OptimizerTimeslot object.
Its availability is constructed by merging the availabilities of self and other,
its constraints by taking the union of both constraint sets.
As an index, the index of self is used.
"""
avail = self.avail.merge_with(other.avail)
constraints = self.constraints.union(other.constraints)
return OptimizerTimeslot(
avail=avail, idx=self.idx, constraints=constraints
)
def __repr__(self) -> str:
return f"({self.avail.simplified}, {self.idx}, {self.constraints})"
TimeslotBlock = list[OptimizerTimeslot]
def merge_blocks(
blocks: Iterable[TimeslotBlock]
) -> Iterable[TimeslotBlock]:
"""Merge iterable of blocks together.
The timeslots of all blocks are grouped into maximal blocks.
Timeslots with the same start and end are identified with each other
and merged (cf `OptimizerTimeslot.merge`).
Throws a ValueError if any timeslots are overlapping but do not
share the same start and end, i.e. partial overlap is not allowed.
:param blocks: iterable of blocks to merge.
:return: iterable of merged blocks.
:rtype: iterable over lists of OptimizerTimeslot objects
"""
if not blocks:
return []
# flatten timeslot iterables to single chain
timeslot_chain = itertools.chain.from_iterable(blocks)
# sort timeslots according to start
timeslots = sorted(
timeslot_chain,
key=lambda slot: slot.avail.start
)
if not timeslots:
return []
all_blocks = []
current_block = [timeslots[0]]
timeslots = timeslots[1:]
for slot in timeslots:
if current_block and slot.avail.overlaps(current_block[-1].avail, strict=True):
if (
slot.avail.start == current_block[-1].avail.start
and slot.avail.end == current_block[-1].avail.end
):
# the same timeslot -> merge
current_block[-1] = current_block[-1].merge(slot)
else:
# partial overlap of interiors -> not supported
raise ValueError(
"Partially overlapping timeslots are not supported!"
f" ({current_block[-1].avail.simplified}, {slot.avail.simplified})"
)
elif not current_block or slot.avail.overlaps(current_block[-1].avail, strict=False):
# only endpoints in intersection -> same block
current_block.append(slot)
else:
# no overlap at all -> new block
all_blocks.append(current_block)
current_block = [slot]
if current_block:
all_blocks.append(current_block)
return all_blocks
class Event(models.Model): class Event(models.Model):
""" """
...@@ -32,8 +141,9 @@ class Event(models.Model): ...@@ -32,8 +141,9 @@ class Event(models.Model):
help_text=_('When should AKs with intention to submit a resolution be done?')) 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, interest_start = models.DateTimeField(verbose_name=_('Interest Window Start'), blank=True, null=True,
help_text= help_text=
_('Opening time for expression of interest. When left blank, no interest indication will be possible.')) _('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, interest_end = models.DateTimeField(verbose_name=_('Interest Window End'), blank=True, null=True,
help_text=_('Closing time for expression of interest.')) help_text=_('Closing time for expression of interest.'))
...@@ -45,16 +155,28 @@ class Event(models.Model): ...@@ -45,16 +155,28 @@ class Event(models.Model):
plan_hidden = models.BooleanField(verbose_name=_('Plan Hidden'), help_text=_('Hides plan for non-staff users'), plan_hidden = models.BooleanField(verbose_name=_('Plan Hidden'), help_text=_('Hides plan for non-staff users'),
default=True) default=True)
plan_published_at = models.DateTimeField(verbose_name=_('Plan published at'), blank=True, null=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'))
poll_hidden = models.BooleanField(verbose_name=_('Poll Hidden'),
help_text=_('Hides preference poll for non-staff users'),
default=True)
poll_published_at = models.DateTimeField(verbose_name=_('Poll published at'), blank=True, null=True,
help_text=_('Timestamp at which the preference poll was published'))
base_url = models.URLField(verbose_name=_("Base URL"), help_text=_("Prefix for wiki link construction"), blank=True) 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) wiki_export_template_name = models.CharField(verbose_name=_("Wiki Export Template Name"), blank=True, max_length=50)
default_slot = models.DecimalField(max_digits=4, decimal_places=2, default=2, verbose_name=_('Default Slot Length'), default_slot = models.DecimalField(max_digits=4, decimal_places=2, default=2, verbose_name=_('Default Slot Length'),
help_text=_('Default length in hours that is assumed for AKs in this event.')) help_text=_('Default length in hours that is assumed for AKs in this event.'))
export_slot = models.DecimalField(max_digits=4, decimal_places=2, default=1, verbose_name=_('Export Slot Length'),
help_text=_(
'Slot duration in hours that is used in the timeslot discretization, '
'when this event is exported for the solver.'
))
contact_email = models.EmailField(verbose_name=_("Contact email address"), blank=True, contact_email = models.EmailField(verbose_name=_("Contact email address"), blank=True,
help_text=_("An email address that is displayed on every page " help_text=_("An email address that is displayed on every page "
"and can be used for all kinds of questions")) "and can be used for all kinds of questions"))
class Meta: class Meta:
verbose_name = _('Event') verbose_name = _('Event')
...@@ -85,11 +207,12 @@ class Event(models.Model): ...@@ -85,11 +207,12 @@ class Event(models.Model):
event = Event.objects.filter(active=True).order_by('start').first() event = Event.objects.filter(active=True).order_by('start').first()
# No active event? Return the next event taking place # No active event? Return the next event taking place
if event is None: 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 return event
def get_categories_with_aks(self, wishes_seperately=False, def get_categories_with_aks(self, wishes_seperately=False,
filter_func=lambda ak: True, hide_empty_categories=False): filter_func=lambda ak: True, hide_empty_categories=False,
types=None, types_all_selected_only=False):
""" """
Get AKCategories as well as a list of AKs belonging to the category for this event Get AKCategories as well as a list of AKs belonging to the category for this event
...@@ -97,6 +220,12 @@ class Event(models.Model): ...@@ -97,6 +220,12 @@ class Event(models.Model):
:type wishes_seperately: bool :type wishes_seperately: bool
:param filter_func: Optional filter predicate, only include AK in list if filter returns True :param filter_func: Optional filter predicate, only include AK in list if filter returns True
:type filter_func: (AK)->bool :type filter_func: (AK)->bool
:param hide_empty_categories: If True, categories with no AKs will not be included in the result
:type hide_empty_categories: bool
:param types: Optional list of AK types to filter by, if None, all types are included
:type types: list[AKType] | None
:param types_all_selected_only: If True, only include AKs that have all of the selected types at the same time
:type types_all_selected_only: bool
:return: list of category-AK-list-tuples, optionally the additional list of AK wishes :return: list of category-AK-list-tuples, optionally the additional list of AK wishes
:rtype: list[(AKCategory, list[AK])] [, list[AK]] :rtype: list[(AKCategory, list[AK])] [, list[AK]]
""" """
...@@ -108,7 +237,7 @@ class Event(models.Model): ...@@ -108,7 +237,7 @@ class Event(models.Model):
# A different behavior is needed depending on whether wishes should show up inside their categories # A different behavior is needed depending on whether wishes should show up inside their categories
# or as a separate category # or as a separate category
def _get_category_aks(category): def _get_category_aks(category, types):
""" """
Get all AKs belonging to a category Get all AKs belonging to a category
Use joining and prefetching to reduce the number of necessary SQL queries Use joining and prefetching to reduce the number of necessary SQL queries
...@@ -117,12 +246,18 @@ class Event(models.Model): ...@@ -117,12 +246,18 @@ class Event(models.Model):
:return: QuerySet over AKs :return: QuerySet over AKs
:return: QuerySet[AK] :return: QuerySet[AK]
""" """
return category.ak_set.select_related('event').prefetch_related('owners', 'akslot_set').all() s = category.ak_set
if types is not None:
s = s.filter(types__in=types).distinct()
if types_all_selected_only:
# TODO fix - this only works in very specific cases
s = s.annotate(Count('types')).filter(types__count=len(types))
return s.select_related('event').prefetch_related('owners', 'akslot_set', 'types').all()
if wishes_seperately: if wishes_seperately:
for category in categories: for category in categories:
ak_list = [] ak_list = []
for ak in _get_category_aks(category): for ak in _get_category_aks(category, types):
if filter_func(ak): if filter_func(ak):
if ak.wish: if ak.wish:
ak_wishes.append(ak) ak_wishes.append(ak)
...@@ -134,7 +269,7 @@ class Event(models.Model): ...@@ -134,7 +269,7 @@ class Event(models.Model):
for category in categories: for category in categories:
ak_list = [] ak_list = []
for ak in _get_category_aks(category): for ak in _get_category_aks(category, types):
if filter_func(ak): if filter_func(ak):
ak_list.append(ak) ak_list.append(ak)
if not hide_empty_categories or len(ak_list) > 0: if not hide_empty_categories or len(ak_list) > 0:
...@@ -162,11 +297,271 @@ class Event(models.Model): ...@@ -162,11 +297,271 @@ class Event(models.Model):
.filter(availabilities__count=0, owners__count__gt=0) .filter(availabilities__count=0, owners__count__gt=0)
) )
def _generate_slots_from_block(
self,
start: datetime,
end: datetime,
slot_duration: timedelta,
*,
slot_index: int = 0,
constraints: set[str] | None = None,
) -> Generator[TimeslotBlock, None, int]:
"""Discretize a time range into timeslots.
Uses a uniform discretization into discrete slots of length `slot_duration`,
starting at `start`. No incomplete timeslots are generated, i.e.
if (`end` - `start`) is not a whole number multiple of `slot_duration`
then the last incomplete timeslot is dropped.
:param start: Start of the time range.
:param end: Start of the time range.
:param slot_duration: Duration of a single timeslot in the discretization.
:param slot_index: index of the first timeslot. Defaults to 0.
:yield: Block of optimizer timeslots as the discretization result.
:ytype: list of OptimizerTimeslot
:return: The first slot index after the yielded blocks, i.e.
`slot_index` + total # generated timeslots
:rtype: int
"""
# local import to prevent cyclic import
# pylint: disable=import-outside-toplevel
from AKModel.availability.models import Availability
current_slot_start = start
previous_slot_start: datetime | None = None
if constraints is None:
constraints = set()
current_block = []
room_availabilities = list({
availability
for room in Room.objects.filter(event=self)
for availability in room.availabilities.all()
})
while current_slot_start + slot_duration <= end:
slot = Availability(
event=self,
start=current_slot_start,
end=current_slot_start + slot_duration,
)
if any((availability.contains(slot) for availability in room_availabilities)):
# no gap in a block
if (
previous_slot_start is not None
and previous_slot_start + slot_duration < current_slot_start
):
yield current_block
current_block = []
current_block.append(
OptimizerTimeslot(avail=slot, idx=slot_index, constraints=constraints)
)
previous_slot_start = current_slot_start
slot_index += 1
current_slot_start += slot_duration
if current_block:
yield current_block
return slot_index
def uniform_time_slots(self, *, slots_in_an_hour: float) -> Iterable[TimeslotBlock]:
"""Uniformly discretize the entire event into blocks of timeslots.
Discretizes entire event uniformly. May not necessarily result in a single block
as slots with no room availability are dropped.
:param slots_in_an_hour: The percentage of an hour covered by a single slot.
Determines the discretization granularity.
:yield: Block of optimizer timeslots as the discretization result.
:ytype: list of OptimizerTimeslot
"""
all_category_constraints = AKCategory.create_category_optimizer_constraints(
AKCategory.objects.filter(event=self).all()
)
yield from self._generate_slots_from_block(
start=self.start,
end=self.end,
slot_duration=timedelta(hours=1.0 / slots_in_an_hour),
constraints=all_category_constraints,
)
def default_time_slots(self, *, slots_in_an_hour: float) -> Iterable[TimeslotBlock]:
"""Discretize all default slots into blocks of timeslots.
In the discretization each default slot corresponds to one block.
:param slots_in_an_hour: The percentage of an hour covered by a single slot.
Determines the discretization granularity.
:yield: Block of optimizer timeslots as the discretization result.
:ytype: list of TimeslotBlock
"""
slot_duration = timedelta(hours=1.0 / slots_in_an_hour)
slot_index = 0
for block_slot in DefaultSlot.objects.filter(event=self).order_by("start", "end"):
category_constraints = AKCategory.create_category_optimizer_constraints(
block_slot.primary_categories.all()
)
slot_index = yield from self._generate_slots_from_block(
start=block_slot.start,
end=block_slot.end,
slot_duration=slot_duration,
slot_index=slot_index,
constraints=category_constraints,
)
def discretize_timeslots(self, *, slots_in_an_hour: float | None = None) -> Iterable[TimeslotBlock]:
""""Choose discretization scheme.
Uses default_time_slots if the event has any DefaultSlot, otherwise uniform_time_slots.
:param slots_in_an_hour: The percentage of an hour covered by a single slot.
Determines the discretization granularity.
:yield: Block of optimizer timeslots as the discretization result.
:ytype: list of TimeslotBlock
"""
if slots_in_an_hour is None:
slots_in_an_hour = 1.0 / float(self.export_slot)
if DefaultSlot.objects.filter(event=self).exists():
# discretize default slots if they exists
yield from merge_blocks(self.default_time_slots(slots_in_an_hour=slots_in_an_hour))
else:
yield from self.uniform_time_slots(slots_in_an_hour=slots_in_an_hour)
@transaction.atomic
def schedule_from_json(
self, schedule: str | dict[str, Any], *, check_for_data_inconsistency: bool = True
) -> int:
"""Load AK schedule from a json string.
:param schedule: A string that can be decoded to json, describing
the AK schedule. The json data is assumed to be constructed
following the output specification of the KoMa conference optimizer, cf.
https://github.com/Die-KoMa/ak-plan-optimierung/wiki/Input-&-output-format
"""
if isinstance(schedule, str):
schedule = json.loads(schedule)
if "input" not in schedule or "scheduled_aks" not in schedule:
raise ValueError(_("Cannot parse malformed JSON input."))
if apps.is_installed("AKSolverInterface") and check_for_data_inconsistency:
from AKSolverInterface.serializers import ExportEventSerializer # pylint: disable=import-outside-toplevel
export_dict = ExportEventSerializer(self).data
if schedule["input"] != export_dict:
raise ValueError(_("Data has changed since the export. Reexport and run the solver again."))
slots_in_an_hour = schedule["input"]["timeslots"]["info"]["duration"]
timeslot_dict = {
timeslot.idx: timeslot
for block in self.discretize_timeslots(slots_in_an_hour=slots_in_an_hour)
for timeslot in block
}
slots_updated = 0
for scheduled_slot in schedule["scheduled_aks"]:
scheduled_slot["timeslot_ids"] = list(map(int, scheduled_slot["timeslot_ids"]))
slot = AKSlot.objects.get(id=int(scheduled_slot["ak_id"]))
if not scheduled_slot["timeslot_ids"]:
raise ValueError(
_("AK {ak_name} is not assigned any timeslot by the solver").format(ak_name=slot.ak.name)
)
start_timeslot = timeslot_dict[min(scheduled_slot["timeslot_ids"])].avail
end_timeslot = timeslot_dict[max(scheduled_slot["timeslot_ids"])].avail
solver_duration = (end_timeslot.end - start_timeslot.start).total_seconds() / 3600.0
if solver_duration + 2e-4 < slot.duration:
raise ValueError(
_(
"Duration of AK {ak_name} assigned by solver ({solver_duration} hours) "
"is less than the duration required by the slot ({slot_duration} hours)"
).format(
ak_name=slot.ak.name,
solver_duration=solver_duration,
slot_duration=slot.duration,
)
)
if slot.fixed:
solver_room = Room.objects.get(id=int(scheduled_slot["room_id"]))
if slot.room != solver_room:
raise ValueError(
_(
"Fixed AK {ak_name} assigned by solver to room {solver_room} "
"is fixed to room {slot_room}"
).format(
ak_name=slot.ak.name,
solver_room=solver_room.name,
slot_room=slot.room.name,
)
)
if slot.start != start_timeslot.start:
raise ValueError(
_(
"Fixed AK {ak_name} assigned by solver to start at {solver_start} "
"is fixed to start at {slot_start}"
).format(
ak_name=slot.ak.name,
solver_start=start_timeslot.start,
slot_start=slot.start,
)
)
else:
slot.room = Room.objects.get(id=int(scheduled_slot["room_id"]))
slot.start = start_timeslot.start
slot.save()
slots_updated += 1
return slots_updated
@property
def rooms(self):
"""Ordered queryset of all rooms associated to this event."""
return Room.objects.filter(event=self).order_by()
@property
def slots(self):
"""Ordered queryset of all AKSlots associated to this event."""
return AKSlot.objects.filter(event=self).order_by()
@property
def participants(self):
"""Ordered queryset of all participants associated to this event."""
if apps.is_installed("AKPreference"):
# local import to prevent cyclic import
# pylint: disable=import-outside-toplevel
from AKPreference.models import EventParticipant
return EventParticipant.objects.filter(event=self).order_by()
return []
@property
def owners(self):
"""Ordered queryset of all AK owners associated to this event."""
return AKOwner.objects.filter(event=self).order_by()
class AKOwner(models.Model): class AKOwner(models.Model):
""" An AKOwner describes the person organizing/holding an AK. """ 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')) 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.')) 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')) link = models.URLField(blank=True, verbose_name=_('Web Link'), help_text=_('Link to Homepage'))
...@@ -245,8 +640,8 @@ class AKCategory(models.Model): ...@@ -245,8 +640,8 @@ class AKCategory(models.Model):
description = models.TextField(blank=True, verbose_name=_("Description"), description = models.TextField(blank=True, verbose_name=_("Description"),
help_text=_("Short description of this AK Category")) help_text=_("Short description of this AK Category"))
present_by_default = models.BooleanField(blank=True, default=True, verbose_name=_("Present by default"), present_by_default = models.BooleanField(blank=True, default=True, verbose_name=_("Present by default"),
help_text=_("Present AKs of this category by default " help_text=_("Present AKs of this category by default if AK owner did not "
"if AK owner did not specify whether this AK should be presented?")) "specify whether this AK should be presented?"))
event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'), event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'),
help_text=_('Associated event')) help_text=_('Associated event'))
...@@ -260,6 +655,20 @@ class AKCategory(models.Model): ...@@ -260,6 +655,20 @@ class AKCategory(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@staticmethod
def create_category_optimizer_constraints(categories: Iterable["AKCategory"]) -> set[str]:
"""Create a set of constraint strings from an AKCategory iterable.
:param categories: The iterable of categories to derive the constraint strings from.
:return: A set of category constraint strings, i.e. strings of the form
'availability-cat-<cat.name>'.
:rtype: set of strings.
"""
return {
f"availability-cat-{cat.name}"
for cat in categories
}
class AKTrack(models.Model): class AKTrack(models.Model):
""" An AKTrack describes a set of semantically related AKs. """ An AKTrack describes a set of semantically related AKs.
...@@ -292,6 +701,8 @@ class AKRequirement(models.Model): ...@@ -292,6 +701,8 @@ class AKRequirement(models.Model):
""" An AKRequirement describes something needed to hold an AK, e.g. infrastructure. """ An AKRequirement describes something needed to hold an AK, e.g. infrastructure.
""" """
name = models.CharField(max_length=128, verbose_name=_('Name'), help_text=_('Name of the Requirement')) name = models.CharField(max_length=128, verbose_name=_('Name'), help_text=_('Name of the Requirement'))
relevant_for_participants = models.BooleanField(default=False, verbose_name=_('Relevant for Participants?'),
help_text=_('Show this requirement when collecting participant preferences'))
event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'), event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'),
help_text=_('Associated event')) help_text=_('Associated event'))
...@@ -311,7 +722,7 @@ class AKType(models.Model): ...@@ -311,7 +722,7 @@ class AKType(models.Model):
or to which group of people it is addressed. Types are specified per event and are an optional feature. 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')) name = models.CharField(max_length=128, verbose_name=_('Name'), help_text=_('Name describing the type'))
slug = models.SlugField(max_length=30, blank=False, verbose_name=_('Slug'),)
event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'), event = models.ForeignKey(to=Event, on_delete=models.CASCADE, verbose_name=_('Event'),
help_text=_('Associated event')) help_text=_('Associated event'))
...@@ -319,7 +730,7 @@ class AKType(models.Model): ...@@ -319,7 +730,7 @@ class AKType(models.Model):
verbose_name = _('AK Type') verbose_name = _('AK Type')
verbose_name_plural = _('AK Types') verbose_name_plural = _('AK Types')
ordering = ['name'] ordering = ['name']
unique_together = ['event', 'name'] unique_together = [['event', 'name'], ['event', 'slug']]
def __str__(self): def __str__(self):
return self.name return self.name
...@@ -328,8 +739,10 @@ class AKType(models.Model): ...@@ -328,8 +739,10 @@ class AKType(models.Model):
class AK(models.Model): class AK(models.Model):
""" An AK is a slot-based activity to be scheduled during an event. """ 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'), 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')) help_text=_('Name displayed in the schedule'))
description = models.TextField(blank=True, verbose_name=_('Description'), help_text=_('Description of the AK')) description = models.TextField(blank=True, verbose_name=_('Description'), help_text=_('Description of the AK'))
...@@ -343,7 +756,7 @@ class AK(models.Model): ...@@ -343,7 +756,7 @@ class AK(models.Model):
category = models.ForeignKey(to=AKCategory, on_delete=models.PROTECT, verbose_name=_('Category'), category = models.ForeignKey(to=AKCategory, on_delete=models.PROTECT, verbose_name=_('Category'),
help_text=_('Category of the AK')) help_text=_('Category of the AK'))
types = models.ManyToManyField(to=AKType, blank=True, verbose_name=_('Types'), types = models.ManyToManyField(to=AKType, blank=True, verbose_name=_('Types'),
help_text=_("This AK is")) help_text=_("This AK is"))
track = models.ForeignKey(to=AKTrack, blank=True, on_delete=models.SET_NULL, null=True, verbose_name=_('Track'), track = models.ForeignKey(to=AKTrack, blank=True, on_delete=models.SET_NULL, null=True, verbose_name=_('Track'),
help_text=_('Track the AK belongs to')) help_text=_('Track the AK belongs to'))
...@@ -361,8 +774,8 @@ class AK(models.Model): ...@@ -361,8 +774,8 @@ class AK(models.Model):
help_text=_('AKs that should precede this AK in the schedule')) help_text=_('AKs that should precede this AK in the schedule'))
notes = models.TextField(blank=True, verbose_name=_('Organizational Notes'), help_text=_( 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 ' '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).')) '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 = models.IntegerField(default=-1, verbose_name=_('Interest'), help_text=_('Expected number of people'))
interest_counter = models.IntegerField(default=0, verbose_name=_('Interest Counter'), interest_counter = models.IntegerField(default=0, verbose_name=_('Interest Counter'),
...@@ -374,7 +787,7 @@ class AK(models.Model): ...@@ -374,7 +787,7 @@ class AK(models.Model):
include_in_export = models.BooleanField(default=True, verbose_name=_('Export?'), include_in_export = models.BooleanField(default=True, verbose_name=_('Export?'),
help_text=_("Include AK in wiki 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: class Meta:
verbose_name = _('AK') verbose_name = _('AK')
...@@ -400,7 +813,7 @@ class AK(models.Model): ...@@ -400,7 +813,7 @@ class AK(models.Model):
availabilities = ', \n'.join(f'{a.simplified}' for a in Availability.objects.select_related('event') availabilities = ', \n'.join(f'{a.simplified}' for a in Availability.objects.select_related('event')
.filter(ak=self)) .filter(ak=self))
detail_string = f"""{self.name}{" (R)" if self.reso else ""}: detail_string = f"""{self.name}{" (R)" if self.reso else ""}:
{self.owners_list} {self.owners_list}
{_('Interest')}: {self.interest}""" {_('Interest')}: {self.interest}"""
...@@ -408,8 +821,22 @@ class AK(models.Model): ...@@ -408,8 +821,22 @@ class AK(models.Model):
detail_string += f"\n{_('Requirements')}: {', '.join(str(r) for r in self.requirements.all())}" detail_string += f"\n{_('Requirements')}: {', '.join(str(r) for r in self.requirements.all())}"
if self.types.count() > 0: if self.types.count() > 0:
detail_string += f"\n{_('Types')}: {', '.join(str(r) for r in self.types.all())}" 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: if self.conflicts.count() > 0:
detail_string += f"\n{_('Conflicts')}: {', '.join(str(c) for c in self.conflicts.all())}" 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: if self.prerequisites.count() > 0:
detail_string += f"\n{_('Prerequisites')}: {', '.join(str(p) for p in self.prerequisites.all())}" detail_string += f"\n{_('Prerequisites')}: {', '.join(str(p) for p in self.prerequisites.all())}"
detail_string += f"\n{_('Availabilities')}: \n{availabilities}" detail_string += f"\n{_('Availabilities')}: \n{availabilities}"
...@@ -418,23 +845,33 @@ class AK(models.Model): ...@@ -418,23 +845,33 @@ class AK(models.Model):
@property @property
def owners_list(self): def owners_list(self):
""" """
Get a list of stringified representations of all owners Get a stringified list of stringified representations of all owners
:return: list of owners :return: stringified list of owners
:rtype: List[str] :rtype: str
""" """
return ", ".join(str(owner) for owner in self.owners.all()) return ", ".join(str(owner) for owner in self.owners.all())
@property @property
def durations_list(self): def durations_list(self):
""" """
Get a list of stringified representations of all durations of associated slots Get a stringified list of stringified representations of all durations of associated slots
:return: list of durations :return: stringified list of durations
:rtype: List[str] :rtype: str
""" """
return ", ".join(str(slot.duration_simplified) for slot in self.akslot_set.select_related('event').all()) return ", ".join(str(slot.duration_simplified) for slot in self.akslot_set.select_related('event').all())
@property
def types_list(self):
"""
Get a stringified list of all types of this AK
:return: stringified list of types
:rtype: str
"""
return ", ".join(str(t) for t in self.types.all())
@property @property
def wish(self): def wish(self):
""" """
...@@ -489,7 +926,7 @@ class AK(models.Model): ...@@ -489,7 +926,7 @@ class AK(models.Model):
return reverse_lazy('submit:ak_detail', kwargs={'event_slug': self.event.slug, 'pk': self.id}) return reverse_lazy('submit:ak_detail', kwargs={'event_slug': self.event.slug, 'pk': self.id})
return self.edit_url return self.edit_url
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None):
# Auto-Generate Link if not set yet # Auto-Generate Link if not set yet
if self.link == "": if self.link == "":
link = self.event.base_url + self.name.replace(" ", "_") link = self.event.base_url + self.name.replace(" ", "_")
...@@ -498,7 +935,8 @@ class AK(models.Model): ...@@ -498,7 +935,8 @@ class AK(models.Model):
# Tell Django that we have updated the link field # Tell Django that we have updated the link field
if update_fields is not None: if update_fields is not None:
update_fields = {"link"}.union(update_fields) update_fields = {"link"}.union(update_fields)
super().save(force_insert, force_update, using, update_fields) super().save(*args,
force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
class Room(models.Model): class Room(models.Model):
...@@ -536,6 +974,32 @@ class Room(models.Model): ...@@ -536,6 +974,32 @@ class Room(models.Model):
def __str__(self): def __str__(self):
return self.title return self.title
def get_time_constraints(self) -> list[str]:
"""Construct list of required time constraint labels."""
# local import to prevent cyclic import
# pylint: disable=import-outside-toplevel
from AKModel.availability.models import Availability
# check if room is available for the whole event
# -> no time constraint needs to be introduced
if Availability.is_event_covered(self.event, self.availabilities.all()):
time_constraints = []
else:
time_constraints = [f"availability-room-{self.pk}"]
return time_constraints
def get_fulfilled_room_constraints(self) -> list[str]:
"""Construct list of fulfilled room constraint labels."""
fulfilled_room_constraints = list(self.properties.values_list("name", flat=True))
fulfilled_room_constraints.append(f"fixed-room-{self.pk}")
if not any(constr.startswith("proxy") for constr in fulfilled_room_constraints):
fulfilled_room_constraints.append("no-proxy")
fulfilled_room_constraints.sort()
return fulfilled_room_constraints
class AKSlot(models.Model): class AKSlot(models.Model):
""" An AK Mapping matches an AK to a room during a certain time. """ An AK Mapping matches an AK to a room during a certain time.
...@@ -615,7 +1079,7 @@ class AKSlot(models.Model): ...@@ -615,7 +1079,7 @@ class AKSlot(models.Model):
def overlaps(self, other: "AKSlot"): def overlaps(self, other: "AKSlot"):
""" """
Check wether two slots overlap Check whether two slots overlap
:param other: second slot to compare with :param other: second slot to compare with
:return: true if they overlap, false if not: :return: true if they overlap, false if not:
...@@ -623,13 +1087,88 @@ class AKSlot(models.Model): ...@@ -623,13 +1087,88 @@ class AKSlot(models.Model):
""" """
return self.start < other.end <= self.end or self.start <= other.start < self.end return self.start < other.end <= self.end or self.start <= other.start < self.end
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None):
# Make sure duration is not longer than the event # Make sure duration is not longer than the event
if update_fields is None or 'duration' in update_fields: if update_fields is None or 'duration' in update_fields:
event_duration = self.event.end - self.event.start event_duration = self.event.end - self.event.start
event_duration_hours = event_duration.days * 24 + event_duration.seconds // 3600 event_duration_hours = event_duration.days * 24 + event_duration.seconds // 3600
self.duration = min(self.duration, event_duration_hours) self.duration = min(self.duration, event_duration_hours)
super().save(force_insert, force_update, using, update_fields) super().save(*args,
force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
def get_room_constraints(self, export_scheduled_aks_as_fixed: bool = False) -> list[str]:
"""Construct list of required room constraint labels."""
room_constraints = list(self.ak.requirements.values_list("name", flat=True).order_by())
if (export_scheduled_aks_as_fixed or self.fixed) and self.room is not None:
room_constraints.append(f"fixed-room-{self.room.pk}")
if not any(constr.startswith("proxy") for constr in room_constraints):
room_constraints.append("no-proxy")
room_constraints.sort()
return room_constraints
def get_time_constraints(self, export_scheduled_aks_as_fixed: bool = False) -> list[str]:
"""Construct list of required time constraint labels."""
# local import to prevent cyclic import
# pylint: disable=import-outside-toplevel
from AKModel.availability.models import Availability
def _owner_time_constraints(owner: AKOwner):
owner_avails = owner.availabilities.all()
if not owner_avails or Availability.is_event_covered(self.event, owner_avails):
return []
return [f"availability-person-{owner.pk}"]
# check if ak resp. owner is available for the whole event
# -> no time constraint needs to be introduced
if (export_scheduled_aks_as_fixed or self.fixed) and self.start is not None:
time_constraints = [f"fixed-akslot-{self.id}"]
elif not Availability.is_event_covered(self.event, self.ak.availabilities.all()):
time_constraints = [f"availability-ak-{self.ak.pk}"]
else:
time_constraints = []
if self.ak.reso:
time_constraints.append("resolution")
for owner in self.ak.owners.all():
time_constraints.extend(_owner_time_constraints(owner))
if self.ak.category:
category_constraints = AKCategory.create_category_optimizer_constraints([self.ak.category])
time_constraints.extend(category_constraints)
time_constraints.sort()
return time_constraints
@property
def export_duration(self) -> int:
"""Number of discrete export timeslots covered by this AKSlot."""
export_duration = self.duration / self.event.export_slot
# We need to return an int, so we round up.
# If the exact result for `export_duration` is an integer `k`,
# FLOP inaccuracies could yield `k + eps`. Then, rounding up
# would return `k + 1` instead of `k`. To avoid this, we subtract
# a small epsilon before rounding.
return math.ceil(export_duration - settings.EXPORT_CEIL_OFFSET_EPS)
@property
def type_names(self):
"""Ordered queryset of the names of all types of this slot's AK."""
return self.ak.types.values_list("name", flat=True).order_by()
@property
def conflict_pks(self) -> list[int]:
"""Ordered queryset of the PKs of all AKSlots that in conflict to this slot."""
conflict_slots = AKSlot.objects.filter(ak__in=self.ak.conflicts.all())
other_ak_slots = AKSlot.objects.filter(ak=self.ak).exclude(pk=self.pk)
return list((conflict_slots | other_ak_slots).values_list("pk", flat=True).order_by())
@property
def depencency_pks(self) -> list[int]:
"""Ordered queryset of the PKs of all AKSlots that this slot depends on."""
dependency_slots = AKSlot.objects.filter(ak__in=self.ak.prerequisites.all())
return list(dependency_slots.values_list("pk", flat=True).order_by())
class AKOrgaMessage(models.Model): class AKOrgaMessage(models.Model):
...@@ -664,6 +1203,7 @@ class ConstraintViolation(models.Model): ...@@ -664,6 +1203,7 @@ class ConstraintViolation(models.Model):
Depending on the type, different fields (references to other models) will be filled. Each violation should always 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 be related to an event and at least on other instance of a causing entity
""" """
class Meta: class Meta:
verbose_name = _('Constraint Violation') verbose_name = _('Constraint Violation')
verbose_name_plural = _('Constraint Violations') verbose_name_plural = _('Constraint Violations')
...@@ -680,7 +1220,7 @@ class ConstraintViolation(models.Model): ...@@ -680,7 +1220,7 @@ class ConstraintViolation(models.Model):
AK_CONFLICT_COLLISION = 'acc', _('AK Slot is scheduled at the same time as an AK listed as a conflict') 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_BEFORE_PREREQUISITE = 'abp', _('AK Slot is scheduled before an AK listed as a prerequisite')
AK_AFTER_RESODEADLINE = 'aar', _( 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_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') 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') ROOM_CAPACITY_EXCEEDED = 'rce', _('Room does not have enough space for interest in scheduled AK Slot')
...@@ -881,6 +1421,7 @@ class DefaultSlot(models.Model): ...@@ -881,6 +1421,7 @@ class DefaultSlot(models.Model):
Model representing a default slot, Model representing a default slot,
i.e., a prefered slot to use for typical AKs in the schedule to guarantee enough breaks etc. i.e., a prefered slot to use for typical AKs in the schedule to guarantee enough breaks etc.
""" """
class Meta: class Meta:
verbose_name = _('Default Slot') verbose_name = _('Default Slot')
verbose_name_plural = _('Default Slots') verbose_name_plural = _('Default Slots')
...@@ -893,7 +1434,8 @@ class DefaultSlot(models.Model): ...@@ -893,7 +1434,8 @@ class DefaultSlot(models.Model):
help_text=_('Associated event')) help_text=_('Associated event'))
primary_categories = models.ManyToManyField(to=AKCategory, verbose_name=_('Primary categories'), blank=True, 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 @property
def start_simplified(self) -> str: def start_simplified(self) -> str:
......
from rest_framework import serializers from rest_framework import serializers
from AKModel.models import AK, Room, AKSlot, AKTrack, AKCategory, AKOwner from AKModel.models import AK, AKCategory, AKOwner, AKSlot, AKTrack, Room
class StringListField(serializers.ListField):
"""List field containing strings."""
child = serializers.CharField()
class IntListField(serializers.ListField):
"""List field containing integers."""
child = serializers.IntegerField()
class AKOwnerSerializer(serializers.ModelSerializer): class AKOwnerSerializer(serializers.ModelSerializer):
......
...@@ -19,6 +19,10 @@ ...@@ -19,6 +19,10 @@
\faUser~ {{ translations.who }} \faUser~ {{ translations.who }}
{% if show_types %}
\faList~ {{ translations.types }}
{% endif %}
\faClock~ {{ translations.duration }} \faClock~ {{ translations.duration }}
\faScroll~{{ translations.reso }} \faScroll~{{ translations.reso }}
...@@ -45,6 +49,10 @@ ...@@ -45,6 +49,10 @@
\faUser~ {{ ak.owners_list | latex_escape }} \faUser~ {{ ak.owners_list | latex_escape }}
{% if show_types %}
\faList~ {{ak.types_list }}
{% endif %}
{% if not result_presentation_mode %} {% if not result_presentation_mode %}
\faClock~ {{ak.durations_list}} \faClock~ {{ak.durations_list}}
{% endif %} {% endif %}
......
...@@ -5,10 +5,21 @@ from django.contrib.auth import get_user_model ...@@ -5,10 +5,21 @@ from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages from django.contrib.messages import get_messages
from django.contrib.messages.storage.base import Message from django.contrib.messages.storage.base import Message
from django.test import TestCase from django.test import TestCase
from django.urls import reverse_lazy, reverse from django.urls import reverse, reverse_lazy
from AKModel.models import Event, AKOwner, AKCategory, AKTrack, AKRequirement, AK, Room, AKSlot, AKOrgaMessage, \ from AKModel.models import (
ConstraintViolation, DefaultSlot AK,
AKCategory,
AKOrgaMessage,
AKOwner,
AKRequirement,
AKSlot,
AKTrack,
ConstraintViolation,
DefaultSlot,
Event,
Room,
)
class BasicViewTests: class BasicViewTests:
...@@ -29,9 +40,10 @@ class BasicViewTests: ...@@ -29,9 +40,10 @@ class BasicViewTests:
since the test framework does not understand the concept of abstract test definitions and would handle this class 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. as real test case otherwise, distorting the test results.
""" """
# pylint: disable=no-member # pylint: disable=no-member
VIEWS = [] VIEWS = []
APP_NAME = '' APP_NAME = ""
VIEWS_STAFF_ONLY = [] VIEWS_STAFF_ONLY = []
EDIT_TESTCASES = [] EDIT_TESTCASES = []
...@@ -41,16 +53,26 @@ class BasicViewTests: ...@@ -41,16 +53,26 @@ class BasicViewTests:
""" """
user_model = get_user_model() user_model = get_user_model()
self.staff_user = user_model.objects.create( self.staff_user = user_model.objects.create(
username='Test Staff User', email='teststaff@example.com', password='staffpw', username="Test Staff User",
is_staff=True, is_active=True email="teststaff@example.com",
password="staffpw",
is_staff=True,
is_active=True,
) )
self.admin_user = user_model.objects.create( self.admin_user = user_model.objects.create(
username='Test Admin User', email='testadmin@example.com', password='adminpw', username="Test Admin User",
is_staff=True, is_superuser=True, is_active=True email="testadmin@example.com",
password="adminpw",
is_staff=True,
is_superuser=True,
is_active=True,
) )
self.deactivated_user = user_model.objects.create( self.deactivated_user = user_model.objects.create(
username='Test Deactivated User', email='testdeactivated@example.com', password='deactivatedpw', username="Test Deactivated User",
is_staff=True, is_active=False email="testdeactivated@example.com",
password="deactivatedpw",
is_staff=True,
is_active=False,
) )
def _name_and_url(self, view_name): def _name_and_url(self, view_name):
...@@ -62,7 +84,9 @@ class BasicViewTests: ...@@ -62,7 +84,9 @@ class BasicViewTests:
:return: full view name with prefix if applicable, url of the view :return: full view name with prefix if applicable, url of the view
:rtype: str, str :rtype: str, str
""" """
view_name_with_prefix = f"{self.APP_NAME}:{view_name[0]}" if self.APP_NAME != "" else view_name[0] view_name_with_prefix = (
f"{self.APP_NAME}:{view_name[0]}" if self.APP_NAME != "" else view_name[0]
)
url = reverse(view_name_with_prefix, kwargs=view_name[1]) url = reverse(view_name_with_prefix, kwargs=view_name[1])
return view_name_with_prefix, url return view_name_with_prefix, url
...@@ -74,7 +98,7 @@ class BasicViewTests: ...@@ -74,7 +98,7 @@ class BasicViewTests:
:param expected_message: message that should be shown :param expected_message: message that should be shown
:param msg_prefix: prefix for the error message when test fails :param msg_prefix: prefix for the error message when test fails
""" """
messages:List[Message] = list(get_messages(response.wsgi_request)) messages: List[Message] = list(get_messages(response.wsgi_request))
msg_count = "No message shown to user" msg_count = "No message shown to user"
msg_content = "Wrong message, expected '{expected_message}'" msg_content = "Wrong message, expected '{expected_message}'"
...@@ -95,10 +119,16 @@ class BasicViewTests: ...@@ -95,10 +119,16 @@ class BasicViewTests:
view_name_with_prefix, url = self._name_and_url(view_name) view_name_with_prefix, url = self._name_and_url(view_name)
try: try:
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, 200, msg=f"{view_name_with_prefix} ({url}) broken") self.assertEqual(
except Exception: # pylint: disable=broad-exception-caught response.status_code,
self.fail(f"An error occurred during rendering of {view_name_with_prefix} ({url}):" 200,
f"\n\n{traceback.format_exc()}") msg=f"{view_name_with_prefix} ({url}) broken",
)
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): def test_access_control_staff_only(self):
""" """
...@@ -107,11 +137,16 @@ class BasicViewTests: ...@@ -107,11 +137,16 @@ class BasicViewTests:
# Not logged in? Views should not be visible # Not logged in? Views should not be visible
self.client.logout() self.client.logout()
for view_name_info in self.VIEWS_STAFF_ONLY: for view_name_info in self.VIEWS_STAFF_ONLY:
expected_response_code = 302 if len(view_name_info) == 2 else view_name_info[2] 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) view_name_with_prefix, url = self._name_and_url(view_name_info)
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, expected_response_code, self.assertEqual(
msg=f"{view_name_with_prefix} ({url}) accessible by non-staff") response.status_code,
expected_response_code,
msg=f"{view_name_with_prefix} ({url}) accessible by non-staff",
)
# Logged in? Views should be visible # Logged in? Views should be visible
self.client.force_login(self.staff_user) self.client.force_login(self.staff_user)
...@@ -119,20 +154,30 @@ class BasicViewTests: ...@@ -119,20 +154,30 @@ class BasicViewTests:
view_name_with_prefix, url = self._name_and_url(view_name_info) view_name_with_prefix, url = self._name_and_url(view_name_info)
try: try:
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, 200, self.assertEqual(
msg=f"{view_name_with_prefix} ({url}) should be accessible for staff (but isn't)") response.status_code,
200,
msg=f"{view_name_with_prefix} ({url}) should be accessible for staff (but isn't)",
)
except Exception: # pylint: disable=broad-exception-caught except Exception: # pylint: disable=broad-exception-caught
self.fail(f"An error occurred during rendering of {view_name_with_prefix} ({url}):" self.fail(
f"\n\n{traceback.format_exc()}") 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 # Disabled user? Views should not be visible
self.client.force_login(self.deactivated_user) self.client.force_login(self.deactivated_user)
for view_name_info in self.VIEWS_STAFF_ONLY: for view_name_info in self.VIEWS_STAFF_ONLY:
expected_response_code = 302 if len(view_name_info) == 2 else view_name_info[2] 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) view_name_with_prefix, url = self._name_and_url(view_name_info)
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, expected_response_code, self.assertEqual(
msg=f"{view_name_with_prefix} ({url}) still accessible for deactivated user") response.status_code,
expected_response_code,
msg=f"{view_name_with_prefix} ({url}) still accessible for deactivated user",
)
def _to_sendable_value(self, val): def _to_sendable_value(self, val):
""" """
...@@ -182,16 +227,26 @@ class BasicViewTests: ...@@ -182,16 +227,26 @@ class BasicViewTests:
self.client.logout() self.client.logout()
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, 200, msg=f"{name}: Could not load edit form via GET ({url})") self.assertEqual(
response.status_code,
200,
msg=f"{name}: Could not load edit form via GET ({url})",
)
form = response.context[form_name] form = response.context[form_name]
data = {k:self._to_sendable_value(v) for k,v in form.initial.items()} data = {k: self._to_sendable_value(v) for k, v in form.initial.items()}
response = self.client.post(url, data=data) response = self.client.post(url, data=data)
if expected_code == 200: if expected_code == 200:
self.assertEqual(response.status_code, 200, msg=f"{name}: Did not return 200 ({url}") self.assertEqual(
response.status_code, 200, msg=f"{name}: Did not return 200 ({url}"
)
elif expected_code == 302: elif expected_code == 302:
self.assertRedirects(response, target_url, msg_prefix=f"{name}: Did not redirect ({url} -> {target_url}") self.assertRedirects(
response,
target_url,
msg_prefix=f"{name}: Did not redirect ({url} -> {target_url}",
)
if expected_message != "": if expected_message != "":
self._assert_message(response, expected_message, msg_prefix=f"{name}") self._assert_message(response, expected_message, msg_prefix=f"{name}")
...@@ -200,30 +255,42 @@ class ModelViewTests(BasicViewTests, TestCase): ...@@ -200,30 +255,42 @@ class ModelViewTests(BasicViewTests, TestCase):
""" """
Basic view test cases for views from AKModel plus some custom tests Basic view test cases for views from AKModel plus some custom tests
""" """
fixtures = ['model.json']
fixtures = ["model.json"]
ADMIN_MODELS = [ ADMIN_MODELS = [
(Event, 'event'), (AKOwner, 'akowner'), (AKCategory, 'akcategory'), (AKTrack, 'aktrack'), (Event, "event"),
(AKRequirement, 'akrequirement'), (AK, 'ak'), (Room, 'room'), (AKSlot, 'akslot'), (AKOwner, "akowner"),
(AKOrgaMessage, 'akorgamessage'), (ConstraintViolation, 'constraintviolation'), (AKCategory, "akcategory"),
(DefaultSlot, 'defaultslot') (AKTrack, "aktrack"),
(AKRequirement, "akrequirement"),
(AK, "ak"),
(Room, "room"),
(AKSlot, "akslot"),
(AKOrgaMessage, "akorgamessage"),
(ConstraintViolation, "constraintviolation"),
(DefaultSlot, "defaultslot"),
] ]
VIEWS_STAFF_ONLY = [ VIEWS_STAFF_ONLY = [
('admin:index', {}), ("admin:index", {}),
('admin:event_status', {'event_slug': 'kif42'}), ("admin:event_status", {"event_slug": "kif42"}),
('admin:event_requirement_overview', {'event_slug': 'kif42'}), ("admin:event_requirement_overview", {"event_slug": "kif42"}),
('admin:ak_csv_export', {'event_slug': 'kif42'}), ("admin:ak_csv_export", {"event_slug": "kif42"}),
('admin:ak_wiki_export', {'slug': 'kif42'}), ("admin:ak_wiki_export", {"slug": "kif42"}),
('admin:ak_delete_orga_messages', {'event_slug': 'kif42'}), ("admin:ak_delete_orga_messages", {"event_slug": "kif42"}),
('admin:ak_slide_export', {'event_slug': 'kif42'}), ("admin:ak_slide_export", {"event_slug": "kif42"}),
('admin:default-slots-editor', {'event_slug': 'kif42'}), ("admin:default-slots-editor", {"event_slug": "kif42"}),
('admin:room-import', {'event_slug': 'kif42'}), ("admin:room-import", {"event_slug": "kif42"}),
('admin:new_event_wizard_start', {}), ("admin:new_event_wizard_start", {}),
] ]
EDIT_TESTCASES = [ EDIT_TESTCASES = [
{'view': 'admin:default-slots-editor', 'kwargs': {'event_slug': 'kif42'}, "admin": True}, {
"view": "admin:default-slots-editor",
"kwargs": {"event_slug": "kif42"},
"admin": True,
},
] ]
def test_admin(self): def test_admin(self):
...@@ -234,24 +301,32 @@ class ModelViewTests(BasicViewTests, TestCase): ...@@ -234,24 +301,32 @@ class ModelViewTests(BasicViewTests, TestCase):
for model in self.ADMIN_MODELS: for model in self.ADMIN_MODELS:
# Special treatment for a subset of views (where we exchanged default functionality, e.g., create views) # Special treatment for a subset of views (where we exchanged default functionality, e.g., create views)
if model[1] == "event": if model[1] == "event":
_, url = self._name_and_url(('admin:new_event_wizard_start', {})) _, url = self._name_and_url(("admin:new_event_wizard_start", {}))
elif model[1] == "room": elif model[1] == "room":
_, url = self._name_and_url(('admin:room-new', {})) _, url = self._name_and_url(("admin:room-new", {}))
# Otherwise, just call the creation form view # Otherwise, just call the creation form view
else: else:
_, 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) response = self.client.get(url)
self.assertEqual(response.status_code, 200, msg=f"Add form for model {model[1]} ({url}) broken") self.assertEqual(
response.status_code,
200,
msg=f"Add form for model {model[1]} ({url}) broken",
)
for model in self.ADMIN_MODELS: for model in self.ADMIN_MODELS:
# Test the update view using the first existing instance of each model # Test the update view using the first existing instance of each model
m = model[0].objects.first() m = model[0].objects.first()
if m is not None: if m is not None:
_, url = self._name_and_url( _, url = self._name_and_url(
(f'admin:AKModel_{model[1]}_change', {'object_id': m.pk}) (f"admin:AKModel_{model[1]}_change", {"object_id": m.pk})
) )
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, 200, msg=f"Edit form for model {model[1]} ({url}) broken") self.assertEqual(
response.status_code,
200,
msg=f"Edit form for model {model[1]} ({url}) broken",
)
def test_wiki_export(self): def test_wiki_export(self):
""" """
...@@ -260,17 +335,27 @@ class ModelViewTests(BasicViewTests, TestCase): ...@@ -260,17 +335,27 @@ class ModelViewTests(BasicViewTests, TestCase):
""" """
self.client.force_login(self.admin_user) self.client.force_login(self.admin_user)
export_url = reverse_lazy("admin:ak_wiki_export", kwargs={'slug': 'kif42'}) export_url = reverse_lazy("admin:ak_wiki_export", kwargs={"slug": "kif42"})
response = self.client.get(export_url) response = self.client.get(export_url)
self.assertEqual(response.status_code, 200, "Export not working at all") self.assertEqual(response.status_code, 200, "Export not working at all")
export_count = 0 export_count = 0
for _, aks in response.context["categories_with_aks"]: for _, aks in response.context["categories_with_aks"]:
for ak in aks: for ak in aks:
self.assertEqual(ak.include_in_export, True, self.assertEqual(
f"AK with export flag set to False (pk={ak.pk}) included in export") ak.include_in_export,
self.assertNotEqual(ak.pk, 1, "AK known to be excluded from export (PK 1) included 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 export_count += 1
self.assertEqual(export_count, AK.objects.filter(event_id=2, include_in_export=True).count(), self.assertEqual(
"Wiki export contained the wrong number of AKs") export_count,
AK.objects.filter(event_id=2, include_in_export=True).count(),
"Wiki export contained the wrong number of AKs",
)
...@@ -4,9 +4,10 @@ from django.urls import include, path ...@@ -4,9 +4,10 @@ from django.urls import include, path
from rest_framework.routers import DefaultRouter from rest_framework.routers import DefaultRouter
import AKModel.views.api import AKModel.views.api
from AKModel.views.manage import ExportSlidesView, PlanPublishView, PlanUnpublishView, DefaultSlotEditorView, \ from AKModel.views.manage import ExportSlidesView, PlanPublishView, PlanUnpublishView, \
AKsByUserView PollPublishView, PollUnpublishView, DefaultSlotEditorView, AKsByUserView
from AKModel.views.ak import AKRequirementOverview, AKCSVExportView, AKWikiExportView, AKMessageDeleteView from AKModel.views.ak import AKRequirementOverview, AKCSVExportView, AKWikiExportView, \
AKMessageDeleteView
from AKModel.views.event_wizard import NewEventWizardStartView, NewEventWizardPrepareImportView, \ from AKModel.views.event_wizard import NewEventWizardStartView, NewEventWizardPrepareImportView, \
NewEventWizardImportView, NewEventWizardActivateView, NewEventWizardFinishView, NewEventWizardSettingsView NewEventWizardImportView, NewEventWizardActivateView, NewEventWizardFinishView, NewEventWizardSettingsView
from AKModel.views.room import RoomBatchCreationView from AKModel.views.room import RoomBatchCreationView
...@@ -44,6 +45,11 @@ if apps.is_installed("AKSubmission"): ...@@ -44,6 +45,11 @@ if apps.is_installed("AKSubmission"):
from AKSubmission.api import increment_interest_counter from AKSubmission.api import increment_interest_counter
extra_paths.append(path('api/ak/<pk>/indicate-interest/', increment_interest_counter, name='submission-ak-indicate-interest')) extra_paths.append(path('api/ak/<pk>/indicate-interest/', increment_interest_counter, name='submission-ak-indicate-interest'))
# If AKSolverInterface is active, register additional API endpoints
if apps.is_installed("AKSolverInterface"):
from AKSolverInterface.api import ExportEventForSolverViewSet
api_router.register("solver-export", ExportEventForSolverViewSet, basename="solver-export")
event_specific_paths = [ event_specific_paths = [
path('api/', include(api_router.urls), name='api'), path('api/', include(api_router.urls), name='api'),
] ]
...@@ -103,6 +109,8 @@ def get_admin_urls_event(admin_site): ...@@ -103,6 +109,8 @@ def get_admin_urls_event(admin_site):
path('<slug:event_slug>/ak-slide-export/', admin_site.admin_view(ExportSlidesView.as_view()), name="ak_slide_export"), path('<slug:event_slug>/ak-slide-export/', admin_site.admin_view(ExportSlidesView.as_view()), name="ak_slide_export"),
path('plan/publish/', admin_site.admin_view(PlanPublishView.as_view()), name="plan-publish"), path('plan/publish/', admin_site.admin_view(PlanPublishView.as_view()), name="plan-publish"),
path('plan/unpublish/', admin_site.admin_view(PlanUnpublishView.as_view()), name="plan-unpublish"), path('plan/unpublish/', admin_site.admin_view(PlanUnpublishView.as_view()), name="plan-unpublish"),
path('poll/publish/', admin_site.admin_view(PollPublishView.as_view()), name="poll-publish"),
path('poll/unpublish/', admin_site.admin_view(PollUnpublishView.as_view()), name="poll-unpublish"),
path('<slug:event_slug>/defaultSlots/', admin_site.admin_view(DefaultSlotEditorView.as_view()), path('<slug:event_slug>/defaultSlots/', admin_site.admin_view(DefaultSlotEditorView.as_view()),
name="default-slots-editor"), name="default-slots-editor"),
path('<slug:event_slug>/importRooms/', admin_site.admin_view(RoomBatchCreationView.as_view()), path('<slug:event_slug>/importRooms/', admin_site.admin_view(RoomBatchCreationView.as_view()),
......
...@@ -8,13 +8,13 @@ from django.contrib import messages ...@@ -8,13 +8,13 @@ from django.contrib import messages
from django.db.models.functions import Now from django.db.models.functions import Now
from django.utils.dateparse import parse_datetime from django.utils.dateparse import parse_datetime
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView, DetailView from django.views.generic import DetailView, ListView, TemplateView
from django_tex.core import render_template_with_context, run_tex_in_directory from django_tex.core import render_template_with_context, run_tex_in_directory
from django_tex.response import PDFResponse from django_tex.response import PDFResponse
from AKModel.forms import SlideExportForm, DefaultSlotEditorForm from AKModel.forms import SlideExportForm, DefaultSlotEditorForm
from AKModel.metaviews.admin import EventSlugMixin, IntermediateAdminView, IntermediateAdminActionView, AdminViewMixin from AKModel.metaviews.admin import EventSlugMixin, IntermediateAdminView, IntermediateAdminActionView, AdminViewMixin
from AKModel.models import ConstraintViolation, Event, DefaultSlot, AKOwner from AKModel.models import ConstraintViolation, Event, DefaultSlot, AKOwner, AKSlot, AKType
class UserView(TemplateView): class UserView(TemplateView):
...@@ -35,6 +35,19 @@ class ExportSlidesView(EventSlugMixin, IntermediateAdminView): ...@@ -35,6 +35,19 @@ class ExportSlidesView(EventSlugMixin, IntermediateAdminView):
title = _('Export AK Slides') title = _('Export AK Slides')
form_class = SlideExportForm form_class = SlideExportForm
def get_form(self, form_class=None):
# Filter type choices to those of the current event
# or completely hide the field if no types are specified for this event
form = super().get_form(form_class)
if self.event.aktype_set.count() > 0:
form.fields['types'].choices = [
(ak_type.id, ak_type.name) for ak_type in self.event.aktype_set.all()
]
else:
form.fields['types'].widget = form.fields['types'].hidden_widget()
form.fields['types_all_selected_only'].widget = form.fields['types_all_selected_only'].hidden_widget()
return form
def form_valid(self, form): def form_valid(self, form):
# pylint: disable=invalid-name # pylint: disable=invalid-name
template_name = 'admin/AKModel/export/slides.tex' template_name = 'admin/AKModel/export/slides.tex'
...@@ -51,6 +64,7 @@ class ExportSlidesView(EventSlugMixin, IntermediateAdminView): ...@@ -51,6 +64,7 @@ class ExportSlidesView(EventSlugMixin, IntermediateAdminView):
'reso': _("Reso intention?"), 'reso': _("Reso intention?"),
'category': _("Category (for Wishes)"), 'category': _("Category (for Wishes)"),
'wishes': _("Wishes"), 'wishes': _("Wishes"),
'types': _("Types"),
} }
def build_ak_list_with_next_aks(ak_list): def build_ak_list_with_next_aks(ak_list):
...@@ -58,23 +72,36 @@ class ExportSlidesView(EventSlugMixin, IntermediateAdminView): ...@@ -58,23 +72,36 @@ class ExportSlidesView(EventSlugMixin, IntermediateAdminView):
Create a list of tuples cosisting of an AK and a list of upcoming AKs (list length depending on setting) Create a list of tuples cosisting of an AK and a list of upcoming AKs (list length depending on setting)
""" """
next_aks_list = zip_longest(*[ak_list[i + 1:] for i in range(NEXT_AK_LIST_LENGTH)], fillvalue=None) next_aks_list = zip_longest(*[ak_list[i + 1:] for i in range(NEXT_AK_LIST_LENGTH)], fillvalue=None)
return [(ak, next_aks) for ak, next_aks in zip_longest(ak_list, next_aks_list, fillvalue=[])] return list(zip_longest(ak_list, next_aks_list, fillvalue=[]))
# Create a list of types to filter AKs by (if at least one type was selected)
types = None
types_filter_string = ""
show_types = self.event.aktype_set.count() > 0
if len(form.cleaned_data['types']) > 0:
types = AKType.objects.filter(id__in=form.cleaned_data['types'])
names_string = ', '.join(AKType.objects.get(pk=t).name for t in form.cleaned_data['types'])
types_filter_string = f"[{_('Type(s)')}: {names_string}]"
types_all_selected_only = form.cleaned_data['types_all_selected_only']
# Get all relevant AKs (wishes separately, and either all AKs or only those who should directly or indirectly # Get all relevant AKs (wishes separately, and either all AKs or only those who should directly or indirectly
# be presented when restriction setting was chosen) # be presented when restriction setting was chosen)
categories_with_aks, ak_wishes = self.event.get_categories_with_aks(wishes_seperately=True, filter_func=lambda categories_with_aks, ak_wishes = self.event.get_categories_with_aks(wishes_seperately=True, filter_func=lambda
ak: not RESULT_PRESENTATION_MODE or (ak.present or (ak.present is None and ak.category.present_by_default))) ak: not RESULT_PRESENTATION_MODE or (ak.present or (ak.present is None and ak.category.present_by_default)),
types=types,
types_all_selected_only=types_all_selected_only)
# Create context for LaTeX rendering # Create context for LaTeX rendering
context = { context = {
'title': self.event.name, 'title': self.event.name,
'categories_with_aks': [(category, build_ak_list_with_next_aks(ak_list)) for category, ak_list in 'categories_with_aks': [(category, build_ak_list_with_next_aks(ak_list)) for category, ak_list in
categories_with_aks], categories_with_aks],
'subtitle': _("AKs"), 'subtitle': _("AKs") + " " + types_filter_string,
"wishes": build_ak_list_with_next_aks(ak_wishes), "wishes": build_ak_list_with_next_aks(ak_wishes),
"translations": translations, "translations": translations,
"result_presentation_mode": RESULT_PRESENTATION_MODE, "result_presentation_mode": RESULT_PRESENTATION_MODE,
"space_for_notes_in_wishes": SPACE_FOR_NOTES_IN_WISHES, "space_for_notes_in_wishes": SPACE_FOR_NOTES_IN_WISHES,
"show_types": show_types,
} }
source = render_template_with_context(template_name, context) source = render_template_with_context(template_name, context)
...@@ -130,6 +157,28 @@ class CVSetLevelWarningView(IntermediateAdminActionView): ...@@ -130,6 +157,28 @@ class CVSetLevelWarningView(IntermediateAdminActionView):
def action(self, form): def action(self, form):
self.entities.update(level=ConstraintViolation.ViolationLevel.WARNING) self.entities.update(level=ConstraintViolation.ViolationLevel.WARNING)
class ClearScheduleView(IntermediateAdminActionView, ListView):
"""
Admin action view: Clear schedule
"""
title = _('Clear schedule')
model = AKSlot
confirmation_message = _('Clear schedule. The following scheduled AKSlots will be reset')
success_message = _('Schedule cleared')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.entities = AKSlot.objects.none()
def get_queryset(self, *args, **kwargs):
query_set = super().get_queryset(*args, **kwargs)
# do not reset fixed AKs
query_set = query_set.filter(fixed=False)
return query_set
def action(self, form):
"""Reset rooms and start for all selected slots."""
self.entities.update(room=None, start=None)
class PlanPublishView(IntermediateAdminActionView): class PlanPublishView(IntermediateAdminActionView):
""" """
...@@ -157,6 +206,31 @@ class PlanUnpublishView(IntermediateAdminActionView): ...@@ -157,6 +206,31 @@ class PlanUnpublishView(IntermediateAdminActionView):
self.entities.update(plan_published_at=None, plan_hidden=True) self.entities.update(plan_published_at=None, plan_hidden=True)
class PollPublishView(IntermediateAdminActionView):
"""
Admin action view: Publish the preference poll of one or multitple event(s)
"""
title = _('Publish preference poll')
model = Event
confirmation_message = _('Publish the poll(s) of:')
success_message = _('Preference poll published')
def action(self, form):
self.entities.update(poll_published_at=Now(), poll_hidden=False)
class PollUnpublishView(IntermediateAdminActionView):
"""
Admin action view: Unpublish the preference poll of one or multitple event(s)
"""
title = _('Unpublish preference poll')
model = Event
confirmation_message = _('Unpublish the preference poll(s) of:')
success_message = _('Preference poll unpublished')
def action(self, form):
self.entities.update(poll_published_at=None, poll_hidden=True)
class DefaultSlotEditorView(EventSlugMixin, IntermediateAdminView): class DefaultSlotEditorView(EventSlugMixin, IntermediateAdminView):
""" """
Admin view: Allow to edit the default slots of an event Admin view: Allow to edit the default slots of an event
......
...@@ -152,6 +152,17 @@ class EventAKsWidget(TemplateStatusWidget): ...@@ -152,6 +152,17 @@ class EventAKsWidget(TemplateStatusWidget):
}, },
] ]
) )
if apps.is_installed("AKSolverInterface"):
actions.extend([
{
"text": _("Export AKs as JSON"),
"url": reverse_lazy("admin:ak_json_export", kwargs={"event_slug": context["event"].slug}),
},
{
"text": _("Import AK schedule from JSON"),
"url": reverse_lazy("admin:ak_schedule_json_import", kwargs={"event_slug": context["event"].slug}),
},
])
return actions return actions
......
...@@ -8,7 +8,7 @@ msgid "" ...@@ -8,7 +8,7 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: PACKAGE VERSION\n" "Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-05-15 20:03+0200\n" "POT-Creation-Date: 2025-06-16 12:44+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n" "Language-Team: LANGUAGE <LL@li.org>\n"
...@@ -38,45 +38,65 @@ msgstr "Veranstaltung" ...@@ -38,45 +38,65 @@ msgstr "Veranstaltung"
#: AKPlan/templates/AKPlan/plan_index.html:59 #: AKPlan/templates/AKPlan/plan_index.html:59
#: AKPlan/templates/AKPlan/plan_room.html:13 #: AKPlan/templates/AKPlan/plan_room.html:13
#: AKPlan/templates/AKPlan/plan_room.html:59 #: AKPlan/templates/AKPlan/plan_room.html:59
#: AKPlan/templates/AKPlan/plan_wall.html:65 #: AKPlan/templates/AKPlan/plan_wall.html:67
msgid "Room" msgid "Room"
msgstr "Raum" msgstr "Raum"
#: AKPlan/templates/AKPlan/plan_index.html:80 #: AKPlan/templates/AKPlan/plan_index.html:120
#: AKPlan/templates/AKPlan/plan_room.html:11 #: AKPlan/templates/AKPlan/plan_room.html:11
#: AKPlan/templates/AKPlan/plan_track.html:9 #: AKPlan/templates/AKPlan/plan_track.html:9
msgid "AK Plan" msgid "AK Plan"
msgstr "AK-Plan" msgstr "AK-Plan"
#: AKPlan/templates/AKPlan/plan_index.html:92 #: AKPlan/templates/AKPlan/plan_index.html:134
#: AKPlan/templates/AKPlan/plan_room.html:49 #: AKPlan/templates/AKPlan/plan_room.html:49
msgid "Rooms" msgid "Rooms"
msgstr "Räume" msgstr "Räume"
#: AKPlan/templates/AKPlan/plan_index.html:105 #: AKPlan/templates/AKPlan/plan_index.html:147
#: AKPlan/templates/AKPlan/plan_track.html:36 #: AKPlan/templates/AKPlan/plan_track.html:36
msgid "Tracks" msgid "Tracks"
msgstr "Tracks" msgstr "Tracks"
#: AKPlan/templates/AKPlan/plan_index.html:117 #: AKPlan/templates/AKPlan/plan_index.html:159
msgid "AK Wall" msgid "AK Wall"
msgstr "AK-Wall" msgstr "AK-Wall"
#: AKPlan/templates/AKPlan/plan_index.html:130 #: AKPlan/templates/AKPlan/plan_index.html:165
#: AKPlan/templates/AKPlan/plan_wall.html:130 msgid "Plan:"
msgstr "Plan:"
#: AKPlan/templates/AKPlan/plan_index.html:171
msgid "Filter by types"
msgstr "Nach Typen filtern"
#: AKPlan/templates/AKPlan/plan_index.html:174
msgid "Types:"
msgstr "Typen:"
#: AKPlan/templates/AKPlan/plan_index.html:182
msgid "AKs without type"
msgstr "AKs ohne Typ"
#: AKPlan/templates/AKPlan/plan_index.html:186
msgid "No AKs with additional other types"
msgstr "Keine AKs, die noch zusätzlich andere Typen haben"
#: AKPlan/templates/AKPlan/plan_index.html:198
#: AKPlan/templates/AKPlan/plan_wall.html:132
msgid "Current AKs" msgid "Current AKs"
msgstr "Aktuelle AKs" msgstr "Aktuelle AKs"
#: AKPlan/templates/AKPlan/plan_index.html:137 #: AKPlan/templates/AKPlan/plan_index.html:205
#: AKPlan/templates/AKPlan/plan_wall.html:135 #: AKPlan/templates/AKPlan/plan_wall.html:137
msgid "Next AKs" msgid "Next AKs"
msgstr "Nächste AKs" msgstr "Nächste AKs"
#: AKPlan/templates/AKPlan/plan_index.html:145 #: AKPlan/templates/AKPlan/plan_index.html:213
msgid "This event is not active." msgid "This event is not active."
msgstr "Dieses Event ist nicht aktiv." msgstr "Dieses Event ist nicht aktiv."
#: AKPlan/templates/AKPlan/plan_index.html:158 #: AKPlan/templates/AKPlan/plan_index.html:226
#: AKPlan/templates/AKPlan/plan_room.html:77 #: AKPlan/templates/AKPlan/plan_room.html:77
#: AKPlan/templates/AKPlan/plan_track.html:58 #: AKPlan/templates/AKPlan/plan_track.html:58
msgid "Plan is not visible (yet)." msgid "Plan is not visible (yet)."
...@@ -99,10 +119,14 @@ msgstr "Eigenschaften" ...@@ -99,10 +119,14 @@ msgstr "Eigenschaften"
msgid "Track" msgid "Track"
msgstr "Track" msgstr "Track"
#: AKPlan/templates/AKPlan/plan_wall.html:145 #: AKPlan/templates/AKPlan/plan_wall.html:147
msgid "Reload page automatically?" msgid "Reload page automatically?"
msgstr "Seite automatisch neu laden?" msgstr "Seite automatisch neu laden?"
#: AKPlan/templates/AKPlan/slots_table.html:14 #: AKPlan/templates/AKPlan/slots_table.html:14
msgid "No AKs" msgid "No AKs"
msgstr "Keine AKs" msgstr "Keine AKs"
#: AKPlan/views.py:64
msgid "Invalid type filter"
msgstr "Ungültiger Typ-Filter"
...@@ -70,6 +70,46 @@ ...@@ -70,6 +70,46 @@
} }
}); });
</script> </script>
{% if type_filtering_active %}
{# Type filter script #}
<script type="module">
const { createApp } = Vue
createApp({
delimiters: ["[[", "]]"],
data() {
return {
types: JSON.parse("{{ types | escapejs }}"),
strict: {{ types_filter_strict|yesno:"true,false" }},
empty: {{ types_filter_empty|yesno:"true,false" }}
}
},
methods: {
onFilterChange(type) {
// Re-generate filter url
const typeString = "types="
+ this.types
.map(t => `${t.slug}:${t.state ? 'yes' : 'no'}`)
.join(',')
+ `&strict=${this.strict ? 'yes' : 'no'}`
+ `&empty=${this.empty ? 'yes' : 'no'}`;
// Redirect to the new url including the adjusted filters
const baseUrl = window.location.origin + window.location.pathname;
window.location.href = `${baseUrl}?${typeString}`;
}
}
}).mount('#filter');
// Prevent showing of cached form values for filter inputs when using broswer navigation
window.addEventListener('pageshow', function(event) {
if (event.persisted) {
window.location.reload();
}
});
</script>
{% endif %}
{% endif %} {% endif %}
{% endblock %} {% endblock %}
...@@ -83,6 +123,8 @@ ...@@ -83,6 +123,8 @@
{% block content %} {% block content %}
{% include "messages.html" %}
<div class="float-end"> <div class="float-end">
<ul class="nav nav-pills"> <ul class="nav nav-pills">
{% if rooms|length > 0 %} {% if rooms|length > 0 %}
...@@ -114,13 +156,39 @@ ...@@ -114,13 +156,39 @@
{% if event.active %} {% if event.active %}
<li class="nav-item"> <li class="nav-item">
<a class="nav-link active" <a class="nav-link active"
href="{% url 'plan:plan_wall' event_slug=event.slug %}">{% fa6_icon 'desktop' 'fas' %}&nbsp;&nbsp;{% trans "AK Wall" %}</a> href="{% url 'plan:plan_wall' event_slug=event.slug %}?{{ query_string }}">{% fa6_icon 'desktop' 'fas' %}&nbsp;&nbsp;{% trans "AK Wall" %}</a>
</li> </li>
{% endif %} {% endif %}
</ul> </ul>
</div> </div>
<h1>Plan: {{ event }}</h1> <h1 class="mb-3">{% trans "Plan:" %} {{ event }}</h1>
{% if type_filtering_active %}
{# Type filter HTML #}
<div class="card border-primary mb-3">
<div class="card-header">
{% trans 'Filter by types' %}
</div>
<div class="card-body d-flex" id="filter">
{% trans "Types:" %}
<div id="filterTypes" class="d-flex">
<div class="form-check form-switch ms-3" v-for="type in types">
<label class="form-check-label" :for="'typeFilterType' + type.slug">[[ type.name ]]</label>
<input class="form-check-input" type="checkbox" :id="'typeFilterType' + type.slug " v-model="type.state" @change="onFilterChange()">
</div>
</div>
<div class="form-check form-switch ms-5">
<label class="form-check-label" for="typeFilterEmpty">{% trans "AKs without type" %}</label>
<input class="form-check-input" type="checkbox" id="typeFilterEmpty" v-model="empty" @change="onFilterChange()">
</div>
<div class="form-check form-switch ms-5">
<label class="form-check-label" for="typeFilterStrict">{% trans "No AKs with additional other types" %}</label>
<input class="form-check-input" type="checkbox" id="typeFilterStrict" v-model="strict" @change="onFilterChange()">>
</div>
</div>
</div>
{% endif %}
{% timezone event.timezone %} {% timezone event.timezone %}
<div class="row" style="margin-top:30px;"> <div class="row" style="margin-top:30px;">
......
from django.test import TestCase from django.test import TestCase
from AKModel.tests import BasicViewTests from AKModel.tests.test_views import BasicViewTests
class PlanViewTests(BasicViewTests, TestCase): class PlanViewTests(BasicViewTests, TestCase):
......
from datetime import timedelta import json
from datetime import datetime, timedelta
from django.conf import settings from django.conf import settings
from django.contrib import messages
from django.db.models import Q
from django.shortcuts import redirect from django.shortcuts import redirect
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.utils.datetime_safe import datetime from django.views.generic import DetailView, ListView
from django.views.generic import ListView, DetailView from django.utils.translation import gettext_lazy as _
from AKModel.models import AKSlot, Room, AKTrack
from AKModel.metaviews.admin import FilterByEventSlugMixin from AKModel.metaviews.admin import FilterByEventSlugMixin
from AKModel.models import AKSlot, AKTrack, Room, AKType
class PlanIndexView(FilterByEventSlugMixin, ListView): class PlanIndexView(FilterByEventSlugMixin, ListView):
...@@ -20,10 +23,69 @@ class PlanIndexView(FilterByEventSlugMixin, ListView): ...@@ -20,10 +23,69 @@ class PlanIndexView(FilterByEventSlugMixin, ListView):
template_name = "AKPlan/plan_index.html" template_name = "AKPlan/plan_index.html"
context_object_name = "akslots" context_object_name = "akslots"
ordering = "start" ordering = "start"
types_filter = None
query_string = ""
def get(self, request, *args, **kwargs):
if 'types' in request.GET:
try:
# Initialize types filter, has to be done here such that it is not reused across requests
self.types_filter = {
"yes": [],
"no": [],
"no_set": set(),
"strict": False,
"empty": False,
}
# If types are given, filter the queryset accordingly
types_raw = request.GET['types'].split(',')
for t in types_raw:
type_slug, type_condition = t.split(':')
if type_condition in ["yes", "no"]:
t = AKType.objects.get(slug=type_slug, event=self.event)
self.types_filter[type_condition].append(t)
if type_condition == "no":
# Store slugs of excluded types in a set for faster lookup
self.types_filter["no_set"].add(t.slug)
else:
raise ValueError(f"Unknown type condition: {type_condition}")
if 'strict' in request.GET:
# If strict is specified and marked as "yes",
# exclude all AKs that have any of the excluded types ("no"),
# even if they have other types that are marked as "yes"
self.types_filter["strict"] = request.GET.get('strict') == 'yes'
if 'empty' in request.GET:
# If empty is specified and marked as "yes", include AKs that have no types at all
self.types_filter["empty"] = request.GET.get('empty') == 'yes'
# Will be used for generating a link to the wall view with the same filter
self.query_string = request.GET.urlencode(safe=",:")
except (ValueError, AKType.DoesNotExist):
# Display an error message if the types parameter is malformed
messages.add_message(request, messages.ERROR, _("Invalid type filter"))
self.types_filter = None
s = super().get(request, *args, **kwargs)
return s
def get_queryset(self): def get_queryset(self):
# Ignore slots not scheduled yet # Ignore slots not scheduled yet
return super().get_queryset().filter(start__isnull=False).select_related('ak', 'room', 'ak__category') qs = (super().get_queryset().filter(start__isnull=False).
select_related('event', 'ak', 'room', 'ak__category', 'ak__event'))
# Need to prefetch both event and ak__event
# since django is not aware that the two are always the same
# Apply type filter if necessary
if self.types_filter:
# Either include all AKs with the given types or without any types at all
if self.types_filter["empty"]:
qs = qs.filter(Q(ak__types__in=self.types_filter["yes"]) | Q(ak__types__isnull=True)).distinct()
# Or only those with the given types
else:
qs = qs.filter(ak__types__in=self.types_filter["yes"]).distinct()
# Afterwards, if strict, exclude all AKs that have any of the excluded types,
# even though they were included by the previous filter
if self.types_filter["strict"]:
qs = qs.exclude(ak__types__in=self.types_filter["no"]).distinct()
return qs
def get_context_data(self, *, object_list=None, **kwargs): def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs) context = super().get_context_data(object_list=object_list, **kwargs)
...@@ -39,6 +101,7 @@ class PlanIndexView(FilterByEventSlugMixin, ListView): ...@@ -39,6 +101,7 @@ class PlanIndexView(FilterByEventSlugMixin, ListView):
# Get list of current and next slots # Get list of current and next slots
for akslot in context["akslots"]: for akslot in context["akslots"]:
self._process_slot(akslot)
# Construct a list of all rooms used by these slots on the fly # Construct a list of all rooms used by these slots on the fly
if akslot.room is not None: if akslot.room is not None:
rooms.add(akslot.room) rooms.add(akslot.room)
...@@ -61,8 +124,38 @@ class PlanIndexView(FilterByEventSlugMixin, ListView): ...@@ -61,8 +124,38 @@ class PlanIndexView(FilterByEventSlugMixin, ListView):
context["tracks"] = self.event.aktrack_set.all() context["tracks"] = self.event.aktrack_set.all()
# Pass query string to template for generating a matching wall link
context["query_string"] = self.query_string
# Generate a list of all types and their current selection state for graphic filtering
types = [{"name": t.name, "slug": t.slug, "state": True} for t in self.event.aktype_set.all()]
if len(types) > 0:
context["type_filtering_active"] = True
if self.types_filter:
for t in types:
if t["slug"] in self.types_filter["no_set"]:
t["state"] = False
# Pass type list as well as filter state for strict filtering and empty types to the template
context["types"] = json.dumps(types)
context["types_filter_strict"] = False
context["types_filter_empty"] = False
if self.types_filter:
context["types_filter_empty"] = self.types_filter["empty"]
context["types_filter_strict"] = self.types_filter["strict"]#
else:
context["type_filtering_active"] = False
return context return context
def _process_slot(self, akslot):
"""
Function to be called for each slot when looping over the slots
(meant to be overridden in inherited views)
:param akslot: current slot
:type akslot: AKSlot
"""
class PlanScreenView(PlanIndexView): class PlanScreenView(PlanIndexView):
""" """
...@@ -96,26 +189,12 @@ class PlanScreenView(PlanIndexView): ...@@ -96,26 +189,12 @@ class PlanScreenView(PlanIndexView):
# Restrict AK slots to relevant ones # Restrict AK slots to relevant ones
# This will automatically filter all rooms not needed for the selected range in the orginal get_context method # This will automatically filter all rooms not needed for the selected range in the orginal get_context method
akslots = super().get_queryset().filter(start__gt=self.start) return super().get_queryset().filter(start__gt=self.start)
def get_context_data(self, *, object_list=None, **kwargs):
# Find the earliest hour AKs start and end (handle 00:00 as 24:00) # Find the earliest hour AKs start and end (handle 00:00 as 24:00)
self.earliest_start_hour = 23 self.earliest_start_hour = 23
self.latest_end_hour = 1 self.latest_end_hour = 1
for akslot in akslots.all():
start_hour = akslot.start.astimezone(self.event.timezone).hour
if start_hour < self.earliest_start_hour:
# Use hour - 1 to improve visibility of date change
self.earliest_start_hour = max(start_hour - 1, 0)
end_hour = akslot.end.astimezone(self.event.timezone).hour
# Special case: AK starts before but ends after midnight -- show until midnight
if end_hour < start_hour:
self.latest_end_hour = 24
elif end_hour > self.latest_end_hour:
# Always use hour + 1, since AK may end at :xy and not always at :00
self.latest_end_hour = min(end_hour + 1, 24)
return akslots
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs) context = super().get_context_data(object_list=object_list, **kwargs)
context["start"] = self.start context["start"] = self.start
context["end"] = self.event.end context["end"] = self.event.end
...@@ -123,6 +202,19 @@ class PlanScreenView(PlanIndexView): ...@@ -123,6 +202,19 @@ class PlanScreenView(PlanIndexView):
context["latest_end_hour"] = self.latest_end_hour context["latest_end_hour"] = self.latest_end_hour
return context return context
def _process_slot(self, akslot):
start_hour = akslot.start.astimezone(self.event.timezone).hour
if start_hour < self.earliest_start_hour:
# Use hour - 1 to improve visibility of date change
self.earliest_start_hour = max(start_hour - 1, 0)
end_hour = akslot.end.astimezone(self.event.timezone).hour
# Special case: AK starts before but ends after midnight -- show until midnight
if end_hour < start_hour:
self.latest_end_hour = 24
elif end_hour > self.latest_end_hour:
# Always use hour + 1, since AK may end at :xy and not always at :00
self.latest_end_hour = min(end_hour + 1, 24)
class PlanRoomView(FilterByEventSlugMixin, DetailView): class PlanRoomView(FilterByEventSlugMixin, DetailView):
""" """
...@@ -152,7 +244,7 @@ class PlanTrackView(FilterByEventSlugMixin, DetailView): ...@@ -152,7 +244,7 @@ class PlanTrackView(FilterByEventSlugMixin, DetailView):
context = super().get_context_data(object_list=object_list, **kwargs) context = super().get_context_data(object_list=object_list, **kwargs)
# Restrict AKSlot list to given track # Restrict AKSlot list to given track
# while joining AK, room and category information to reduce the amount of necessary SQL queries # while joining AK, room and category information to reduce the amount of necessary SQL queries
context["slots"] = AKSlot.objects.\ context["slots"] = AKSlot.objects. \
filter(event=self.event, ak__track=context['track']).\ filter(event=self.event, ak__track=context['track']). \
select_related('ak', 'room', 'ak__category') select_related('ak', 'room', 'ak__category')
return context return context
...@@ -10,6 +10,7 @@ For the full list of settings and their values, see ...@@ -10,6 +10,7 @@ For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/ https://docs.djangoproject.com/en/2.2/ref/settings/
""" """
import decimal
import os import os
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
...@@ -38,6 +39,8 @@ INSTALLED_APPS = [ ...@@ -38,6 +39,8 @@ INSTALLED_APPS = [
'AKScheduling.apps.AkschedulingConfig', 'AKScheduling.apps.AkschedulingConfig',
'AKPlan.apps.AkplanConfig', 'AKPlan.apps.AkplanConfig',
'AKOnline.apps.AkonlineConfig', 'AKOnline.apps.AkonlineConfig',
'AKPreference.apps.AkpreferenceConfig',
'AKSolverInterface.apps.AksolverinterfaceConfig',
'AKModel.apps.AKAdminConfig', 'AKModel.apps.AKAdminConfig',
'django.contrib.auth', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.contenttypes',
...@@ -221,6 +224,12 @@ DASHBOARD_RECENT_MAX = 25 ...@@ -221,6 +224,12 @@ DASHBOARD_RECENT_MAX = 25
# (active events will always be featured, even if their number is higher than this threshold) # (active events will always be featured, even if their number is higher than this threshold)
DASHBOARD_MAX_FEATURED_EVENTS = 3 DASHBOARD_MAX_FEATURED_EVENTS = 3
# In the export to the solver we need to calculate the integer number
# of discrete time slots covered by an AK. This is done by rounding
# the 'exact' number up. To avoid 'overshooting' by 1
# due to FLOP inaccuracies, we subtract this small epsilon before rounding.
EXPORT_CEIL_OFFSET_EPS = decimal.Decimal(1e-4)
# Registration/login behavior # Registration/login behavior
SIMPLE_BACKEND_REDIRECT_URL = "/user/" SIMPLE_BACKEND_REDIRECT_URL = "/user/"
LOGIN_REDIRECT_URL = SIMPLE_BACKEND_REDIRECT_URL LOGIN_REDIRECT_URL = SIMPLE_BACKEND_REDIRECT_URL
......
...@@ -37,3 +37,5 @@ if apps.is_installed("AKDashboard"): ...@@ -37,3 +37,5 @@ if apps.is_installed("AKDashboard"):
urlpatterns.append(path('', include('AKDashboard.urls', namespace='dashboard'))) urlpatterns.append(path('', include('AKDashboard.urls', namespace='dashboard')))
if apps.is_installed("AKPlan"): if apps.is_installed("AKPlan"):
urlpatterns.append(path('', include('AKPlan.urls', namespace='plan'))) urlpatterns.append(path('', include('AKPlan.urls', namespace='plan')))
if apps.is_installed("AKPreference"):
urlpatterns.append(path('', include('AKPreference.urls', namespace='poll')))
from django import forms
from django.contrib import admin
from AKPreference.models import AKPreference, EventParticipant
from AKModel.admin import PrepopulateWithNextActiveEventMixin, EventRelatedFieldListFilter
from AKModel.models import AK
@admin.register(EventParticipant)
class EventParticipantAdmin(PrepopulateWithNextActiveEventMixin, admin.ModelAdmin):
"""
Admin interface for EventParticipant
"""
model = EventParticipant
list_display = ['name', 'institution', 'event']
list_filter = ['event', 'institution']
list_editable = []
ordering = ['name']
class AKPreferenceAdminForm(forms.ModelForm):
"""
Adapted admin form for AK preferences for usage in :class:`AKPreferenceAdmin`)
"""
class Meta:
widgets = {
'participant': forms.Select,
'ak': forms.Select,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Filter possible values for foreign keys & m2m when event is specified
if hasattr(self.instance, "event") and self.instance.event is not None:
self.fields["participant"].queryset = EventParticipant.objects.filter(event=self.instance.event)
self.fields["ak"].queryset = AK.objects.filter(event=self.instance.event)
@admin.register(AKPreference)
class AKPreferenceAdmin(PrepopulateWithNextActiveEventMixin, admin.ModelAdmin):
"""
Admin interface for AK preferences.
Uses an adapted form (see :class:`AKPreferenceAdminForm`)
"""
model = AKPreference
form = AKPreferenceAdminForm
list_display = ['preference', 'participant', 'ak', 'event']
list_filter = ['event', ('ak', EventRelatedFieldListFilter), ('participant', EventRelatedFieldListFilter)]
list_editable = []
ordering = ['participant', 'preference', 'ak']