Skip to content
Snippets Groups Projects

Compare revisions

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

Source

Select target project
No results found

Target

Select target project
  • konstantin/akplanning
  • matedealer/akplanning
  • kif/akplanning
  • mirco/akplanning
  • lordofthevoid/akplanning
  • voidptr/akplanning
  • xayomer/akplanning-fork
  • mollux/akplanning
  • neumantm/akplanning
  • mmarx/akplanning
  • nerf/akplanning
  • felix_bonn/akplanning
  • sebastian.uschmann/akplanning
13 results
Show changes
Showing
with 2218 additions and 71 deletions
{% for track in tracks.all %}
<a href="{% url 'submit:ak_list_by_track' event_slug=event_slug track_pk=track.pk %}"><span
class="badge bg-info">{{ track }}</span></a>
{% endfor %}
from django import template
from fontawesome_6.templatetags.fontawesome_6 import fa6_icon
register = template.Library()
@register.filter
def bool_symbol(bool_val):
"""
Show a nice icon instead of the string true/false
:param bool_val: boolean value to iconify
:return: check or times icon depending on the value
"""
if bool_val:
return fa6_icon("check", "fas")
return fa6_icon("times", "fas")
@register.inclusion_tag("AKSubmission/tracks_list.html")
def track_list(tracks, event_slug):
"""
Generate a clickable list of tracks (one badge per track) based upon the tracks_list template
:param tracks: tracks to consider
:param event_slug: slug of this event, required for link creation
:return: html fragment containing track links
"""
return {"tracks": tracks, "event_slug": event_slug}
@register.inclusion_tag("AKSubmission/category_list.html")
def category_list(categories, event_slug):
"""
Generate a clickable list of categories (one badge per category) based upon the category_list template
:param categories: categories to consider
:param event_slug: slug of this event, required for link creation
:return: html fragment containing category links
"""
return {"categories": categories, "event_slug": event_slug}
@register.inclusion_tag("AKSubmission/category_linked_badge.html")
def category_linked_badge(category, event_slug):
"""
Generate a clickable category badge based upon the category_linked_badge template
:param category: category to show/link
:param event_slug: slug of this event, required for link creation
:return: html fragment containing badge
"""
return {"category": category, "event_slug": event_slug}
from datetime import datetime, timedelta
from django.test import TestCase
from django.urls import reverse_lazy
from AKModel.models import AK, AKSlot, Event
from AKModel.tests import BasicViewTests
from AKSubmission.forms import AKSubmissionForm
class ModelViewTests(BasicViewTests, TestCase):
"""
Testcases for AKSubmission app.
This extends :class:`BasicViewTests` for standard view and edit testcases
that are specified in this class as VIEWS and EDIT_TESTCASES.
Additionally several additional testcases, in particular to test the API
and the dispatching for owner selection and editing are specified.
"""
fixtures = ['model.json']
VIEWS = [
('submission_overview', {'event_slug': 'kif42'}),
('ak_detail', {'event_slug': 'kif42', 'pk': 1}),
('ak_history', {'event_slug': 'kif42', 'pk': 1}),
('ak_edit', {'event_slug': 'kif42', 'pk': 1}),
('akslot_add', {'event_slug': 'kif42', 'pk': 1}),
('akmessage_add', {'event_slug': 'kif42', 'pk': 1}),
('akslot_edit', {'event_slug': 'kif42', 'pk': 5}),
('akslot_delete', {'event_slug': 'kif42', 'pk': 5}),
('ak_list', {'event_slug': 'kif42'}),
('ak_list_by_category', {'event_slug': 'kif42', 'category_pk': 4}),
('ak_list_by_track', {'event_slug': 'kif42', 'track_pk': 1}),
('akowner_create', {'event_slug': 'kif42'}),
('akowner_edit', {'event_slug': 'kif42', 'slug': 'a'}),
('submit_ak', {'event_slug': 'kif42', 'owner_slug': 'a'}),
('submit_ak_wish', {'event_slug': 'kif42'}),
('error_not_configured', {'event_slug': 'kif42'}),
]
APP_NAME = 'submit'
EDIT_TESTCASES = [
{'view': 'ak_edit', 'target_view': 'ak_detail', 'kwargs': {'event_slug': 'kif42', 'pk': 1},
'expected_message': "AK successfully updated"},
{'view': 'akslot_edit', 'target_view': 'ak_detail', 'kwargs': {'event_slug': 'kif42', 'pk': 5},
'target_kwargs': {'event_slug': 'kif42', 'pk': 1}, 'expected_message': "AK Slot successfully updated"},
{'view': 'akowner_edit', 'target_view': 'submission_overview', 'kwargs': {'event_slug': 'kif42', 'slug': 'a'},
'target_kwargs': {'event_slug': 'kif42'}, 'expected_message': "Person Info successfully updated"},
]
def test_akslot_edit_delete_prevention(self):
"""
Slots planned already may not be modified or deleted in front end
"""
self.client.logout()
_, url = self._name_and_url(('akslot_edit', {'event_slug': 'kif42', 'pk': 1}))
response = self.client.get(url)
self.assertEqual(response.status_code, 302,
msg=f"AK Slot editing ({url}) possible even though slot was already scheduled")
self._assert_message(response, "You cannot edit a slot that has already been scheduled")
_, url = self._name_and_url(('akslot_delete', {'event_slug': 'kif42', 'pk': 1}))
response = self.client.get(url)
self.assertEqual(response.status_code, 302,
msg=f"AK Slot deletion ({url}) possible even though slot was already scheduled")
self._assert_message(response, "You cannot delete a slot that has already been scheduled")
def test_slot_creation_deletion(self):
"""
Test creation and deletion of slots in frontend
"""
ak_args = {'event_slug': 'kif42', 'pk': 1}
redirect_url = reverse_lazy(f"{self.APP_NAME}:ak_detail", kwargs=ak_args)
# Create a valid slot -> Redirect to AK detail page, message to user
count_slots = AK.objects.get(pk=1).akslot_set.count()
create_url = reverse_lazy(f"{self.APP_NAME}:akslot_add", kwargs=ak_args)
response = self.client.post(create_url, {'ak': 1, 'event': 2, 'duration': 1.5})
self.assertRedirects(response, redirect_url, status_code=302, target_status_code=200,
msg_prefix="Did not correctly trigger redirect")
self.assertEqual(AK.objects.get(pk=1).akslot_set.count(), count_slots + 1,
msg="New slot was not correctly saved")
# Get primary key of newly created Slot
slot_pk = AK.objects.get(pk=1).akslot_set.order_by('pk').last().pk
# Edit the recently created slot: Make sure view is accessible, post change
# -> redirect to detail page, duration updated
edit_url = reverse_lazy(f"{self.APP_NAME}:akslot_edit", kwargs={'event_slug': 'kif42', 'pk': slot_pk})
response = self.client.get(edit_url)
self.assertEqual(response.status_code, 200, msg=f"Cant open edit view for newly created slot ({edit_url})")
response = self.client.post(edit_url, {'ak': 1, 'event': 2, 'duration': 2})
self.assertRedirects(response, redirect_url, status_code=302, target_status_code=200,
msg_prefix="Did not correctly trigger redirect")
self.assertEqual(AKSlot.objects.get(pk=slot_pk).duration, 2,
msg="Slot was not correctly changed")
# Delete recently created slot: Make sure view is accessible, post deletion
# -> redirect to detail page, slot deleted, message to user
deletion_url = reverse_lazy(f"{self.APP_NAME}:akslot_delete", kwargs={'event_slug': 'kif42', 'pk': slot_pk})
response = self.client.get(deletion_url)
self.assertEqual(response.status_code, 200,
msg="Cant open deletion view for newly created slot ({deletion_url})")
response = self.client.post(deletion_url, {})
self.assertRedirects(response, redirect_url, status_code=302, target_status_code=200,
msg_prefix="Did not correctly trigger redirect")
self.assertFalse(AKSlot.objects.filter(pk=slot_pk).exists(), msg="Slot was not correctly deleted")
self.assertEqual(AK.objects.get(pk=1).akslot_set.count(), count_slots, msg="AK still has to many slots")
def test_ak_owner_editing(self):
"""
Test dispatch of user editing requests
"""
edit_url = reverse_lazy(f"{self.APP_NAME}:akowner_edit_dispatch", kwargs={'event_slug': 'kif42'})
base_url = reverse_lazy(f"{self.APP_NAME}:submission_overview", kwargs={'event_slug': 'kif42'})
# Empty form/no user selected -> start page
response = self.client.post(edit_url, {'owner_id': -1})
self.assertRedirects(response, base_url, status_code=302, target_status_code=200,
msg_prefix="Did not redirect to start page even though no user was selected")
self._assert_message(response, "No user selected")
# Correct selection -> user edit page for that user
edit_redirect_url = reverse_lazy(f"{self.APP_NAME}:akowner_edit", kwargs={'event_slug': 'kif42', 'slug': 'a'})
response = self.client.post(edit_url, {'owner_id': 1})
self.assertRedirects(response, edit_redirect_url, status_code=302, target_status_code=200,
msg_prefix=f"Dispatch redirect failed (should go to {edit_redirect_url})")
def test_ak_owner_selection(self):
"""
Test dispatch of owner selection requests
"""
select_url = reverse_lazy(f"{self.APP_NAME}:akowner_select", kwargs={'event_slug': 'kif42'})
create_url = reverse_lazy(f"{self.APP_NAME}:akowner_create", kwargs={'event_slug': 'kif42'})
# Empty user selection -> create a new user view
response = self.client.post(select_url, {'owner_id': -1})
self.assertRedirects(response, create_url, status_code=302, target_status_code=200,
msg_prefix="Did not redirect to user create view even though no user was specified")
# Valid user selected -> redirect to view that allows to add a new AK with this user as owner
add_redirect_url = reverse_lazy(f"{self.APP_NAME}:submit_ak", kwargs={'event_slug': 'kif42', 'owner_slug': 'a'})
response = self.client.post(select_url, {'owner_id': 1})
self.assertRedirects(response, add_redirect_url, status_code=302, target_status_code=200,
msg_prefix=f"Dispatch redirect to ak submission page failed "
f"(should go to {add_redirect_url})")
def test_orga_message_submission(self):
"""
Test submission and storing of direct confident messages to organizers
"""
form_url = reverse_lazy(f"{self.APP_NAME}:akmessage_add", kwargs={'event_slug': 'kif42', 'pk': 1})
detail_url = reverse_lazy(f"{self.APP_NAME}:ak_detail", kwargs={'event_slug': 'kif42', 'pk': 1})
count_messages = AK.objects.get(pk=1).akorgamessage_set.count()
# Test that submission view is accessible
response = self.client.get(form_url)
self.assertEqual(response.status_code, 200, msg="Could not load message form view")
# Test submission itself and the following redirect -> AK detail page
response = self.client.post(form_url, {'ak': 1, 'event': 2, 'text': 'Test message text'})
self.assertRedirects(response, detail_url, status_code=302, target_status_code=200,
msg_prefix=f"Did not trigger redirect to ak detail page ({detail_url})")
# Make sure message was correctly saved in database and user is notified about that
self._assert_message(response, "Message to organizers successfully saved")
self.assertEqual(AK.objects.get(pk=1).akorgamessage_set.count(), count_messages + 1,
msg="Message was not correctly saved")
def test_interest_api(self):
"""
Test interest indicating API (access, functionality)
"""
interest_api_url = "/kif42/api/ak/1/indicate-interest/"
ak = AK.objects.get(pk=1)
event = Event.objects.get(slug='kif42')
ak_interest_counter = ak.interest_counter
# Check Access method (only POST)
response = self.client.get(interest_api_url)
self.assertEqual(response.status_code, 405, "Should not be accessible via GET")
event.interest_start = datetime.now().astimezone(event.timezone) + timedelta(minutes=-10)
event.interest_end = datetime.now().astimezone(event.timezone) + timedelta(minutes=+10)
event.save()
# Test correct indication -> HTTP 200, counter increased
response = self.client.post(interest_api_url)
self.assertEqual(response.status_code, 200, f"API end point not working ({interest_api_url})")
self.assertEqual(AK.objects.get(pk=1).interest_counter, ak_interest_counter + 1, "Counter was not increased")
event.interest_end = datetime.now().astimezone(event.timezone) + timedelta(minutes=-2)
event.save()
# Test indication outside of indication window -> HTTP 403, counter not increased
response = self.client.post(interest_api_url)
self.assertEqual(response.status_code, 403,
"API end point still reachable even though interest indication window ended "
"({interest_api_url})")
self.assertEqual(AK.objects.get(pk=1).interest_counter, ak_interest_counter + 1,
"Counter was increased even though interest indication window ended")
# Test call for non-existing AK -> HTTP 403
invalid_interest_api_url = "/kif42/api/ak/-1/indicate-interest/"
response = self.client.post(invalid_interest_api_url)
self.assertEqual(response.status_code, 404, f"Invalid URL reachable ({interest_api_url})")
def test_adding_of_unknown_user(self):
"""
Test adding of a previously not existing owner to an AK
"""
# Pre-Check: AK detail page existing?
detail_url = reverse_lazy(f"{self.APP_NAME}:ak_detail", kwargs={'event_slug': 'kif42', 'pk': 1})
response = self.client.get(detail_url)
self.assertEqual(response.status_code, 200, msg="Could not load ak detail view")
# Make sure AK detail page contains a link to add a new owner
edit_url = reverse_lazy(f"{self.APP_NAME}:ak_edit", kwargs={'event_slug': 'kif42', 'pk': 1})
response = self.client.get(edit_url)
self.assertEqual(response.status_code, 200, msg="Could not load ak detail view")
self.assertContains(response, "Add person not in the list yet",
msg_prefix="Link to add unknown user not contained")
# Check adding of a new owner by posting an according request
# -> Redirect to AK detail page, message to user, owners list updated
self.assertEqual(AK.objects.get(pk=1).owners.count(), 1)
add_new_user_to_ak_url = reverse_lazy(f"{self.APP_NAME}:akowner_create", kwargs={'event_slug': 'kif42'}) \
+ "?add_to_existing_ak=1"
response = self.client.post(add_new_user_to_ak_url,
{'name': 'New test owner', 'event': Event.get_by_slug('kif42').pk})
self.assertRedirects(response, detail_url,
msg_prefix=f"No correct redirect: {add_new_user_to_ak_url} (POST) -> {detail_url}")
self._assert_message(response, "Added 'New test owner' as new owner of 'Test AK Inhalt'")
self.assertEqual(AK.objects.get(pk=1).owners.count(), 2)
def test_visibility_requirements_in_submission_form(self):
"""
Test visibility of requirements field in submission form
"""
event = Event.get_by_slug('kif42')
form = AKSubmissionForm(data={'name': 'Test AK', 'event': event}, instance=None, initial={"event": event})
self.assertIn('requirements', form.fields,
msg="Requirements field not present in form even though event has requirements")
event2 = Event.objects.create(name='Event without requirements',
slug='no_req',
start=datetime.now().astimezone(event.timezone),
end=datetime.now().astimezone(event.timezone),
active=True)
form2 = AKSubmissionForm(data={'name': 'Test AK', 'event': event2}, instance=None, initial={"event": event2})
self.assertNotIn('requirements', form2.fields,
msg="Requirements field should not be present for events without requirements")
def test_visibility_types_in_submission_form(self):
"""
Test visibility of types field in submission form
"""
event = Event.get_by_slug('kif42')
form = AKSubmissionForm(data={'name': 'Test AK', 'event': event}, instance=None, initial={"event": event})
self.assertIn('types', form.fields,
msg="Requirements field not present in form even though event has requirements")
event2 = Event.objects.create(name='Event without types',
slug='no_types',
start=datetime.now().astimezone(event.timezone),
end=datetime.now().astimezone(event.timezone),
active=True)
form2 = AKSubmissionForm(data={'name': 'Test AK', 'event': event2}, instance=None, initial={"event": event2})
self.assertNotIn('types', form2.fields,
msg="Requirements field should not be present for events without types")
from django.urls import path, include
from . import views
app_name = "submit"
urlpatterns = [
path(
'<slug:event_slug>/submission/',
include([
path('', views.SubmissionOverviewView.as_view(), name='submission_overview'),
path('ak/<int:pk>/', views.AKDetailView.as_view(), name='ak_detail'),
path('ak/<int:pk>/history/', views.AKHistoryView.as_view(), name='ak_history'),
path('ak/<int:pk>/edit/', views.AKEditView.as_view(), name='ak_edit'),
path('ak/<int:pk>/add_slot/', views.AKSlotAddView.as_view(), name='akslot_add'),
path('ak/<int:pk>/add_message/', views.AKAddOrgaMessageView.as_view(), name='akmessage_add'),
path('akslot/<int:pk>/edit/', views.AKSlotEditView.as_view(), name='akslot_edit'),
path('akslot/<int:pk>/delete/', views.AKSlotDeleteView.as_view(), name='akslot_delete'),
path('aks/', views.AKOverviewView.as_view(), name='ak_list'),
path('aks/category/<int:category_pk>/', views.AKListByCategoryView.as_view(), name='ak_list_by_category'),
path('aks/track/<int:track_pk>/', views.AKListByTrackView.as_view(), name='ak_list_by_track'),
path('owner/', views.AKOwnerCreateView.as_view(), name='akowner_create'),
path('new/', views.AKOwnerSelectDispatchView.as_view(), name='akowner_select'),
path('owner/edit/', views.AKOwnerEditDispatchView.as_view(), name='akowner_edit_dispatch'),
path('<slug:slug>/edit/', views.AKOwnerEditView.as_view(), name='akowner_edit'),
path('<slug:owner_slug>/new/', views.AKSubmissionView.as_view(), name='submit_ak'),
path('new_wish/', views.AKWishSubmissionView.as_view(), name='submit_ak_wish'),
path('error/', views.SubmissionErrorNotConfiguredView.as_view(), name='error_not_configured'),
])
),
]
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from math import floor
from django.apps import apps
from django.conf import settings
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
from django.views import View
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView
from AKModel.availability.models import Availability
from AKModel.metaviews import status_manager
from AKModel.metaviews.admin import EventSlugMixin, FilterByEventSlugMixin
from AKModel.metaviews.status import TemplateStatusWidget
from AKModel.models import AK, AKCategory, AKOrgaMessage, AKOwner, AKSlot, AKTrack
from AKSubmission.api import ak_interest_indication_active
from AKSubmission.forms import AKDurationForm, AKForm, AKOrgaMessageForm, AKOwnerForm, AKSubmissionForm, AKWishForm
class SubmissionErrorNotConfiguredView(EventSlugMixin, TemplateView):
"""
View to show when submission is not correctly configured yet for this event
and hence the submission component cannot be used already.
"""
template_name = "AKSubmission/submission_not_configured.html"
class AKOverviewView(FilterByEventSlugMixin, ListView):
"""
View: Show a tabbed list of AKs belonging to this event split by categories
Wishes show up in between of the other AKs in the category they belong to.
In contrast to :class:`SubmissionOverviewView` that inherits from this view,
on this view there is no form to add new AKs or edit owners.
Since the inherited version of this view will have a slightly different behaviour,
this view contains multiple methods that can be overriden for this adaption.
"""
model = AKCategory
context_object_name = "categories"
template_name = "AKSubmission/ak_overview.html"
wishes_as_category = False
def filter_aks(self, context, category): # pylint: disable=unused-argument
"""
Filter which AKs to display based on the given context and category
In the default case, all AKs of that category are returned (including wishes)
:param context: context of the view
:param category: category to filter the AK list for
:return: filtered list of AKs for the given category
:rtype: QuerySet[AK]
"""
# Use prefetching and relation selection/joining to reduce the amount of necessary queries
return category.ak_set.select_related('event').prefetch_related('owners').prefetch_related('types').all()
def get_active_category_name(self, context):
"""
Get the category name to display by default/before further user interaction
In the default case, simply the first category (the one with the lowest ID for this event) is used
:param context: context of the view
:return: name of the default category
:rtype: str
"""
return context["categories_with_aks"][0][0].name
def get_table_title(self, context): # pylint: disable=unused-argument
"""
Specify the title above the AK list/table in this view
:param context: context of the view
:return: title to use
:rtype: str
"""
return _("All AKs")
def get(self, request, *args, **kwargs):
"""
Handle GET request
Overriden to allow checking for correct configuration and
redirect to error page if necessary (see :class:`SubmissionErrorNotConfiguredView`)
"""
self._load_event()
self.object_list = self.get_queryset() # pylint: disable=attribute-defined-outside-init
# No categories yet? Redirect to configuration error page
if self.object_list.count() == 0:
return redirect(reverse_lazy("submit:error_not_configured", kwargs={'event_slug': self.event.slug}))
context = self.get_context_data()
return self.render_to_response(context)
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
# ==========================================================
# Sort AKs into different lists (by their category)
# ==========================================================
ak_wishes = []
categories_with_aks = []
# Loop over categories, load AKs (while filtering them if necessary) and create a list of (category, aks)-tuples
# Depending on the setting of self.wishes_as_category, wishes are either included
# or added to a special "Wish"-Category that is created on-the-fly to provide consistent handling in the
# template (without storing it in the database)
for category in context["categories"]:
aks_for_category = []
for ak in self.filter_aks(context, category):
if self.wishes_as_category and ak.wish:
ak_wishes.append(ak)
else:
aks_for_category.append(ak)
categories_with_aks.append((category, aks_for_category))
if self.wishes_as_category:
categories_with_aks.append(
(AKCategory(name=_("Wishes"), pk=0, description=_("AKs one would like to have")), ak_wishes))
context["categories_with_aks"] = categories_with_aks
context["active_category"] = self.get_active_category_name(context)
context['table_title'] = self.get_table_title(context)
context['show_types'] = self.event.aktype_set.count() > 0
# ==========================================================
# Display interest indication button?
# ==========================================================
current_timestamp = datetime.now().astimezone(self.event.timezone)
context['interest_indication_active'] = ak_interest_indication_active(self.event, current_timestamp)
return context
class SubmissionOverviewView(AKOverviewView):
"""
View: List of AKs and possibility to add AKs or adapt owner information
Main/start view of the component.
This view inherits from :class:`AKOverviewView`, but treats wishes as separate category if requested in the settings
and handles the change actions mentioned above.
"""
model = AKCategory
context_object_name = "categories"
template_name = "AKSubmission/submission_overview.html"
# this mainly steers the different handling of wishes
# since the code for that is already included in the parent class
wishes_as_category = settings.WISHES_AS_CATEGORY
def get_table_title(self, context):
"""
Specify the title above the AK list/table in this view
:param context: context of the view
:return: title to use
:rtype: str
"""
return _("Currently planned AKs")
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
# Get list of existing owners for event (for AK submission start)
context["existingOwners"] = AKOwner.objects.filter(event=self.event)
return context
class AKListByCategoryView(AKOverviewView):
"""
View: List of only the AKs belonging to a certain category.
This view inherits from :class:`AKOverviewView`, but produces only one list instead of a tabbed one.
"""
def dispatch(self, request, *args, **kwargs):
# Override dispatching
# Needed to handle the checking whether the category exists
# noinspection PyAttributeOutsideInit
# pylint: disable=attribute-defined-outside-init
self.category = get_object_or_404(AKCategory, pk=kwargs['category_pk'])
return super().dispatch(request, *args, **kwargs)
def get_active_category_name(self, context):
"""
Get the category name to display by default/before further user interaction
In this case, this will be the name of the category specified via pk
:param context: context of the view
:return: name of the category
:rtype: str
"""
return self.category.name
class AKListByTrackView(AKOverviewView):
"""
View: List of only the AKs belonging to a certain track.
This view inherits from :class:`AKOverviewView` and there will be one list per category
-- but only AKs of a certain given track will be included in them.
"""
def dispatch(self, request, *args, **kwargs):
# Override dispatching
# Needed to handle the checking whether the track exists
self.track = get_object_or_404(AKTrack, pk=kwargs['track_pk']) # pylint: disable=attribute-defined-outside-init
return super().dispatch(request, *args, **kwargs)
def filter_aks(self, context, category):
"""
Filter which AKs to display based on the given context and category
In this case, the list is further restricted by the track
:param context: context of the view
:param category: category to filter the AK list for
:return: filtered list of AKs for the given category
:rtype: QuerySet[AK]
"""
return super().filter_aks(context, category).filter(track=self.track)
def get_table_title(self, context):
return f"{_('AKs with Track')} = {self.track.name}"
class AKDetailView(EventSlugMixin, DetailView):
"""
View: AK Details
"""
model = AK
context_object_name = "ak"
template_name = "AKSubmission/ak_detail.html"
def get_queryset(self):
# Get information about the AK and do some query optimization
return super().get_queryset().select_related('event').prefetch_related('owners')
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
context["availabilities"] = Availability.objects.filter(ak=context["ak"])
current_timestamp = datetime.now().astimezone(self.event.timezone)
# Is this AK taking place now or soon (used for top page visualization)
context["featured_slot_type"] = "NONE"
if apps.is_installed("AKPlan"):
in_two_hours = current_timestamp + timedelta(hours=2)
slots = context["ak"].akslot_set.filter(start__isnull=False, room__isnull=False).select_related('room')
for slot in slots:
if slot.end > current_timestamp:
if slot.start <= current_timestamp:
context["featured_slot_type"] = "CURRENT"
remaining = slot.end - current_timestamp
elif slot.start <= in_two_hours:
context["featured_slot_type"] = "UPCOMING"
remaining = slot.start - current_timestamp
else:
continue
context["featured_slot"] = slot
context["featured_slot_remaining"] = floor(remaining.days * 24 * 60 + remaining.seconds / 60)
break
# Display interest indication button?
context['interest_indication_active'] = ak_interest_indication_active(self.event, current_timestamp)
return context
class AKHistoryView(EventSlugMixin, DetailView):
"""
View: Show history of a given AK
"""
model = AK
context_object_name = "ak"
template_name = "AKSubmission/ak_history.html"
class EventInactiveRedirectMixin:
"""
Mixin that will cause a redirect when actions are performed on an inactive event.
Will add a message explaining why the action was not performed to the user
and then redirect to start page of the submission component
"""
def get_error_message(self):
"""
Error message to display after redirect (can be adjusted by this method)
:return: error message
:rtype: str
"""
return _("Event inactive. Cannot create or update.")
def get(self, request, *args, **kwargs):
"""
Override GET request handling
Will either perform the redirect including the message creation or continue with the planned dispatching
"""
s = super().get(request, *args, **kwargs)
if not self.event.active:
messages.add_message(self.request, messages.ERROR, self.get_error_message())
return redirect(reverse_lazy('submit:submission_overview', kwargs={'event_slug': self.event.slug}))
return s
class AKAndAKWishSubmissionView(EventSlugMixin, EventInactiveRedirectMixin, CreateView):
"""
View: Submission form for AKs and Wishes
Base view, will be used by :class:`AKSubmissionView` and :class:`AKWishSubmissionView`
"""
model = AK
template_name = 'AKSubmission/submit_new.html'
form_class = AKSubmissionForm
def get_success_url(self):
messages.add_message(self.request, messages.SUCCESS, _("AK successfully created"))
return self.object.detail_url
def form_valid(self, form):
if not form.cleaned_data["event"].active:
messages.add_message(self.request, messages.ERROR, self.get_error_message())
return redirect(reverse_lazy('submit:submission_overview',
kwargs={'event_slug': form.cleaned_data["event"].slug}))
# Try to save AK and get redirect URL
super_form_valid = super().form_valid(form)
# Generate slot(s) (but not for wishes)
if "durations" in form.cleaned_data:
for duration in form.cleaned_data["durations"]:
new_slot = AKSlot(ak=self.object, duration=duration, event=self.object.event)
new_slot.save()
return super_form_valid
class AKSubmissionView(AKAndAKWishSubmissionView):
"""
View: AK submission form
Extends :class:`AKAndAKWishSubmissionView`
"""
def get_initial(self):
# Load initial values for the form
# Used to directly add the first owner and the event this AK will belong to
initials = super(AKAndAKWishSubmissionView, self).get_initial()
initials['owners'] = [AKOwner.get_by_slug(self.event, self.kwargs['owner_slug'])]
initials['event'] = self.event
return initials
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
context['owner'] = get_object_or_404(AKOwner, event=self.event, slug=self.kwargs['owner_slug'])
return context
class AKWishSubmissionView(AKAndAKWishSubmissionView):
"""
View: Wish submission form
Extends :class:`AKAndAKWishSubmissionView`
"""
template_name = 'AKSubmission/submit_new_wish.html'
form_class = AKWishForm
def get_initial(self):
# Load initial values for the form
# Used to directly select the event this AK will belong to
initials = super(AKAndAKWishSubmissionView, self).get_initial()
initials['event'] = self.event
return initials
class AKEditView(EventSlugMixin, EventInactiveRedirectMixin, UpdateView):
"""
View: Update an AK
This allows to change most fields of an AK as specified in :class:`AKSubmission.forms.AKForm`,
including the availabilities.
It will also handle the change from AK to wish and vice versa (triggered by adding or removing owners)
and automatically create or delete (unscheduled) slots
"""
model = AK
template_name = 'AKSubmission/ak_edit.html'
form_class = AKForm
def get_success_url(self):
# Redirection after successfully saving to detail page of AK where also a success message is displayed
messages.add_message(self.request, messages.SUCCESS, _("AK successfully updated"))
return self.object.detail_url
def form_valid(self, form):
# Handle valid form submission
# Only save when event is active, otherwise redirect
if not form.cleaned_data["event"].active:
messages.add_message(self.request, messages.ERROR, self.get_error_message())
return redirect(reverse_lazy('submit:submission_overview',
kwargs={'event_slug': form.cleaned_data["event"].slug}))
# Remember owner count before saving to know whether the AK changed its state between AK and wish
previous_owner_count = self.object.owners.count()
# Perform saving and redirect handling by calling default/parent implementation of form_valid
redirect_response = super().form_valid(form)
# Did this AK change from wish to AK or vice versa?
new_owner_count = self.object.owners.count()
# Now AK:
if previous_owner_count == 0 and new_owner_count > 0 and self.object.akslot_set.count() == 0:
# Create one slot with default length
AKSlot.objects.create(ak=self.object, duration=self.object.event.default_slot, event=self.object.event)
# Now wish:
elif previous_owner_count > 0 and new_owner_count == 0:
# Delete all unscheduled slots
self.object.akslot_set.filter(start__isnull=True).delete()
# Redirect to success url
return redirect_response
class AKOwnerCreateView(EventSlugMixin, EventInactiveRedirectMixin, CreateView):
"""
View: Create a new owner
"""
model = AKOwner
template_name = 'AKSubmission/akowner_create_update.html'
form_class = AKOwnerForm
def get_success_url(self):
# The redirect url depends on the source this view was called from:
# Called from an existing AK? Add the new owner as an owner of that AK, notify the user and redirect to detail
# page of that AK
if "add_to_existing_ak" in self.request.GET:
ak_pk = self.request.GET['add_to_existing_ak']
ak = get_object_or_404(AK, pk=ak_pk)
ak.owners.add(self.object)
messages.add_message(self.request, messages.SUCCESS,
_("Added '{owner}' as new owner of '{ak.name}'").format(owner=self.object, ak=ak))
return ak.detail_url
# Called from the submission overview? Offer the user to create a new AK with the recently created owner
# prefilled as owner of that AK in the creation form
return reverse_lazy('submit:submit_ak',
kwargs={'event_slug': self.kwargs['event_slug'], 'owner_slug': self.object.slug})
def get_initial(self):
# Set the event in the (hidden) event field in the form based on the URL this view was called with
initials = super().get_initial()
initials['event'] = self.event
return initials
def form_valid(self, form):
# Prevent changes if event is not active
if not form.cleaned_data["event"].active:
messages.add_message(self.request, messages.ERROR, self.get_error_message())
return redirect(reverse_lazy('submit:submission_overview',
kwargs={'event_slug': form.cleaned_data["event"].slug}))
return super().form_valid(form)
class AKOwnerDispatchView(ABC, EventSlugMixin, View):
"""
Base view: Dispatch to correct view based upon
Will be used by :class:`AKOwnerSelectDispatchView` and :class:`AKOwnerEditDispatchView` to handle button clicks for
"New AK" and "Edit Person Info" in submission overview based upon the selection in the owner dropdown field
"""
@abstractmethod
def get_new_owner_redirect(self, event_slug):
"""
Get redirect when user selected "I do not own AKs yet"
:param event_slug: slug of the event, needed for constructing redirect
:return: redirect to perform
:rtype: HttpResponseRedirect
"""
@abstractmethod
def get_valid_owner_redirect(self, event_slug, owner):
"""
Get redirect when user selected "I do not own AKs yet"
:param event_slug: slug of the event, needed for constructing redirect
:param owner: owner to perform the dispatching for
:return: redirect to perform
:rtype: HttpResponseRedirect
"""
def post(self, request, *args, **kwargs):
# This view is solely meant to handle POST requests
# Perform dispatching based on the submitted owner_id
# No owner_id? Redirect to submission overview view
if "owner_id" not in request.POST:
return redirect('submit:submission_overview', event_slug=kwargs['event_slug'])
owner_id = request.POST["owner_id"]
# Special owner_id "-1" (value of "I do not own AKs yet)? Redirect to owner creation view
if owner_id == "-1":
return self.get_new_owner_redirect(kwargs['event_slug'])
# Normal owner_id given? Check vor validity and redirect to AK submission page with that owner prefilled
# or display a 404 error page if no owner for the given id can be found. The latter should only happen when the
# user manipulated the value before sending or when the owner was deleted in backend and the user did not
# reload the dropdown between deletion and sending the dispatch request
owner = get_object_or_404(AKOwner, pk=request.POST["owner_id"])
return self.get_valid_owner_redirect(kwargs['event_slug'], owner)
def get(self, request, *args, **kwargs):
# This view should never be called with GET, perform a redirect to overview in that case
return redirect('submit:submission_overview', event_slug=kwargs['event_slug'])
class AKOwnerSelectDispatchView(AKOwnerDispatchView):
"""
View: Handle submission from the owner selection dropdown in submission overview for AK creation
("New AK" button)
This view will perform redirects depending on the selection in the owner dropdown field.
Based upon the abstract base view :class:`AKOwnerDispatchView`.
"""
def get_new_owner_redirect(self, event_slug):
return redirect('submit:akowner_create', event_slug=event_slug)
def get_valid_owner_redirect(self, event_slug, owner):
return redirect('submit:submit_ak', event_slug=event_slug, owner_slug=owner.slug)
class AKOwnerEditDispatchView(AKOwnerDispatchView):
"""
View: Handle submission from the owner selection dropdown in submission overview for owner editing
("Edit Person Info" button)
This view will perform redirects depending on the selection in the owner dropdown field.
Based upon the abstract base view :class:`AKOwnerDispatchView`.
"""
def get_new_owner_redirect(self, event_slug):
messages.add_message(self.request, messages.WARNING, _("No user selected"))
return redirect('submit:submission_overview', event_slug)
def get_valid_owner_redirect(self, event_slug, owner):
return redirect('submit:akowner_edit', event_slug=event_slug, slug=owner.slug)
class AKOwnerEditView(FilterByEventSlugMixin, EventSlugMixin, EventInactiveRedirectMixin, UpdateView):
"""
View: Edit an owner
"""
model = AKOwner
template_name = "AKSubmission/akowner_create_update.html"
form_class = AKOwnerForm
def get_success_url(self):
messages.add_message(self.request, messages.SUCCESS, _("Person Info successfully updated"))
return reverse_lazy('submit:submission_overview', kwargs={'event_slug': self.kwargs['event_slug']})
def form_valid(self, form):
# Prevent updating if event is not active
if not form.cleaned_data["event"].active:
messages.add_message(self.request, messages.ERROR, self.get_error_message())
return redirect(reverse_lazy('submit:submission_overview',
kwargs={'event_slug': form.cleaned_data["event"].slug}))
return super().form_valid(form)
class AKSlotAddView(EventSlugMixin, EventInactiveRedirectMixin, CreateView):
"""
View: Add an additional slot to an AK
The user has to select the duration of the slot in this view
The view will only process the request when the event is active (as steered by :class:`EventInactiveRedirectMixin`)
"""
model = AKSlot
form_class = AKDurationForm
template_name = "AKSubmission/akslot_add_update.html"
def get_initial(self):
initials = super().get_initial()
initials['event'] = self.event
initials['ak'] = get_object_or_404(AK, pk=self.kwargs['pk'])
initials['duration'] = self.event.default_slot
return initials
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
context['ak'] = get_object_or_404(AK, pk=self.kwargs['pk'])
return context
def get_success_url(self):
messages.add_message(self.request, messages.SUCCESS, _("AK Slot successfully added"))
return self.object.ak.detail_url
class AKSlotEditView(EventSlugMixin, EventInactiveRedirectMixin, UpdateView):
"""
View: Update the duration of an AK slot
The view will only process the request when the event is active (as steered by :class:`EventInactiveRedirectMixin`)
and only slots that are not scheduled yet may be changed
"""
model = AKSlot
form_class = AKDurationForm
template_name = "AKSubmission/akslot_add_update.html"
def get(self, request, *args, **kwargs):
akslot = get_object_or_404(AKSlot, pk=kwargs["pk"])
if akslot.start is not None:
messages.add_message(self.request, messages.WARNING,
_("You cannot edit a slot that has already been scheduled"))
return HttpResponseRedirect(akslot.ak.detail_url)
return super().get(request, *args, **kwargs)
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
context['ak'] = self.object.ak
return context
def get_success_url(self):
messages.add_message(self.request, messages.SUCCESS, _("AK Slot successfully updated"))
return self.object.ak.detail_url
class AKSlotDeleteView(EventSlugMixin, EventInactiveRedirectMixin, DeleteView):
"""
View: Delete an AK slot
The view will only process the request when the event is active (as steered by :class:`EventInactiveRedirectMixin`)
and only slots that are not scheduled yet may be deleted
"""
model = AKSlot
template_name = "AKSubmission/akslot_delete.html"
def get(self, request, *args, **kwargs):
akslot = get_object_or_404(AKSlot, pk=kwargs["pk"])
if akslot.start is not None:
messages.add_message(self.request, messages.WARNING,
_("You cannot delete a slot that has already been scheduled"))
return HttpResponseRedirect(akslot.ak.detail_url)
return super().get(request, *args, **kwargs)
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
context['ak'] = self.object.ak
return context
def get_success_url(self):
messages.add_message(self.request, messages.SUCCESS, _("AK Slot successfully deleted"))
return self.object.ak.detail_url
@status_manager.register(name="event_ak_messages")
class EventAKMessagesWidget(TemplateStatusWidget):
"""
Status page widget: AK Messages
A widget to display information about AK-related messages sent to organizers for the given event
"""
required_context_type = "event"
title = _("Messages")
template_name = "admin/AKModel/render_ak_messages.html"
def get_context_data(self, context) -> dict:
context["ak_messages"] = AKOrgaMessage.objects.filter(ak__event=context["event"])
return context
def render_actions(self, context: {}) -> list[dict]:
return [
{
"text": _("Delete all messages"),
"url": reverse_lazy("admin:ak_delete_orga_messages", kwargs={"event_slug": context["event"].slug}),
},
]
class AKAddOrgaMessageView(EventSlugMixin, CreateView):
"""
View: Form to create a (confidential) message to the organizers as defined in
:class:`AKSubmission.forms.AKOrgaMessageForm`
"""
model = AKOrgaMessage
form_class = AKOrgaMessageForm
template_name = "AKSubmission/akmessage_add.html"
def get_initial(self):
initials = super().get_initial()
initials['ak'] = get_object_or_404(AK, pk=self.kwargs['pk'])
initials['event'] = initials['ak'].event
return initials
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(object_list=object_list, **kwargs)
context['ak'] = get_object_or_404(AK, pk=self.kwargs['pk'])
return context
def get_success_url(self):
messages.add_message(self.request, messages.SUCCESS, _("Message to organizers successfully saved"))
return self.object.ak.detail_url
......@@ -61,7 +61,7 @@ Provide more context by answering these questions:
Include details about your configuration and environment:
* **Which version (commit)) are you using?**
* **Which version (commit) are you using?**
* **What's the OS you're using**?
### Suggesting Enhancements
......
......@@ -14,4 +14,6 @@ AKPlanning is currently being maintained by:
Further contributions in the form of code, testing, documentation etc. were made by:
*
* R. Zameitat [xayomer](https://gitlab.fachschaften.org/xayomer)
* N. Steinger [voidptr](https://gitlab.fachschaften.org/voidptr)
* T. Neumann [neumantm](https://gitlab.fachschaften.org/neumantm)
FROM python:3-alpine
RUN apk add --no-cache gcc python3-dev musl-dev libffi-dev mariadb-connector-c-dev gettext
ADD . /app
WORKDIR /app
RUN pip install -r requirements.txt -r .docker/extra_requirements.txt
ENV DJANGO_SETTINGS_MODULE=AKPlanning.settings_production
RUN mkdir /app/AKPlanning/settings
EXPOSE 3035
CMD ["sh", "/app/.docker/entrypoint.sh"]
# AK Planning: Setup
This repository contains a Django project with several apps.
## Requirements
AKPlanning has two types of requirements: System requirements are dependent on operating system and need to be installed
manually beforehand. Python requirements will be installed inside a virtual environment (strongly recommended) during
setup.
### System Requirements
* Python3.11+ incl. development tools
* Virtualenv
* pdflatex & beamer
class (`texlive-latex-base texlive-latex-recommended texlive-latex-extra texlive-fonts-extra texlive-luatex`)
* for production using uwsgi:
* C compiler e.g. gcc
* uwsgi
* uwsgi Python3 plugin
* for production using Apache (in addition to uwsgi)
* the mod proxy uwsgi plugin for apache2
### Python Requirements
Python requirements are listed in ``requirements.txt``. They can be installed with pip using ``-r requirements.txt``.
## Development Setup
* create a new directory that should contain the files in future, e.g. ``mkdir AKPlanning``
* change into that directory ``cd AKPlanning``
* clone this repository ``git clone URL .``
### Automatic Setup
1. execute the setup bash script ``Utils/setup.sh``
### Manual Setup
1. setup a virtual environment using the proper python version ``virtualenv venv -p python3.7``
1. activate virtualenv ``source venv/bin/activate``
1. install python requirements ``pip install -r requirements.txt``
1. setup necessary database tables etc. ``python manage.py migrate``
1. prepare static files (can be omitted for dev setups) ``python manage.py collectstatic``
1. compile translations ``python manage.py compilemessages``
1. create a priviledged user, credentials are entered interactively on CLI ``python manage.py createsuperuser``
1. deactivate virtualenv ``deactivate``
### Development Server
**Do not use this for deployment!**
To start the application for development, in the root directory,
1. activate virtualenv ``source venv/bin/activate``
1. start development server ``python manage.py runserver 0:8000``
1. In your browser, access ``http://127.0.0.1:8000/admin/`` and continue from there.
## Deployment Setup
This application can be deployed using a web server as any other Django application. Remember to use a secret key that
is not stored in any repository or similar, and disable DEBUG mode (``settings.py``).
**Step-by-Step Instructions**
1. log into your system with a sudo user
1. install system requirements
1. create a folder, e.g. ``mkdir /srv/AKPlanning/``
1. change to the new directory ``cd /srv/AKPlanning/``
1. clone this repository ``git clone URL .``
1. setup a virtual environment using the proper python version ``virtualenv venv -p python3.7``
1. activate virtualenv ``source venv/bin/activate``
1. update tools ``pip install --upgrade setuptools pip wheel``
1. install python requirements ``pip install -r requirements.txt``
1. create the file ``AKPlanning/settings_secrets.py`` (copy from ``settings_secrets.py.sample``) and fill it with the
necessary secrets (e.g. generated by ``tr -dc 'a-z0-9!@#$%^&*(-_=+)' < /dev/urandom | head -c50``) (it is a good idea
to restrict read permissions from others)
1. if necessary enable uwsgi proxy plugin for Apache e.g.``a2enmod proxy_uwsgi``
1. edit the apache config to serve the application and the static files, e.g. on a dedicated system
in ``/etc/apache2/sites-enabled/000-default.conf`` within the ``VirtualHost`` tag add:
```
Alias /static /srv/AKPlanning/static
<Directory /srv/AKPlanning/static>
Require all granted
</Directory>
ProxyPassMatch ^/static/ !
ProxyPass / uwsgi://127.0.0.1:3035/
```
or create a new config (.conf) file (similar to ``apache-akplanning.conf``) replacing $SUBDOMAIN with the subdomain
the system should be available under, and $MAILADDRESS with the e-mail address of your administrator and $PATHTO with
the appropriate paths. Copy or symlink it to ``/etc/apache2/sites-available``. Then symlink it to ``sites-enabled``
e.g. by using ``ln -s /etc/apache2/sites-available/akplanning.conf /etc/apache2/sites-enabled/akplanning.conf``.
1. restart Apache ``sudo systemctl restart apache2.service``
1. create a dedicated user, e.g. ``adduser django``
1. transfer ownership of the folder to the new user ``chown -R django:django /srv/AKPlanning``
1. Copy or symlink the uwsgi config in ``uwsgi-akplanning.ini`` to ``/etc/uwsgi/apps-available/`` and then symlink it
to ``/etc/uwsgi/apps-enabled/`` using
e.g., ``ln -s /srv/AKPlanning/uwsgi-akplanning.ini /etc/uwsgi/apps-available/akplanning.ini``
and ``ln -s /etc/uwsgi/apps-available/akplanning.ini /etc/uwsgi/apps-enabled/akplanning.ini``
start uwsgi using the configuration file ``uwsgi --ini uwsgi-akplanning.ini``
1. restart uwsgi ``sudo systemctl restart uwsgi``
1. execute the update script ``./Utils/update.sh --prod``
## Deployment Setup using Docker
This project also provides a docker file for easy deployment.
The container described by the docker file only contains the project itself.
Additional containers for the database and webserver are needed to use it.
The following [docker-compose](https://docs.docker.com/compose/) file shows a typical usage:
```
version: "3"
networks:
akplanning:
external: false
volumes:
static-files:
services:
mariadb:
image: mariadb:10
restart: always
environment:
MYSQL_ROOT_PASSWORD: supermegasecrey
MYSQL_DATABASE: akplanning
MYSQL_USER: akplanning
MYSQL_PASSWORD: secret
TZ: Europe/Berlin
networks:
- akplanning
akplanning-server:
image: neumantm/akplanning:2021-03-10
restart: always
environment:
SECRET_KEY: superlongandsupersecret
DB_HOST: mariadb
DB_USER: akplanning
DB_NAME: akplanning
DB_PASSWORD: secret
HOSTS: "['akplanning.example.net', 'akplanning.example.de']"
TZ: Europe/Berlin
AUTO_MIGRATE_DB: 'true'
DJANGO_SUPERUSER_USERNAME: admin
DJANGO_SUPERUSER_EMAIL: admin@example.com
DJANGO_SUPERUSER_PASSWORD: supersecret
EXTRA_DJANGO_SETTING_FOO: DJANGO_FOO = True\nDJANGO_BAR = False
depends_on:
- mariadb
networks:
- akplanning
volumes:
- static-files:/app/static
web-server:
image: nginx
restart: always
volumes:
- /path/to/nginx.conf:/etc/nginx/nginx.conf:ro
- static-files:/var/www/akplanning-static
ports:
- "8080:80"
depends_on:
- akplanning-server
networks:
- akplanning
```
The `nginx.conf` would look like this:
```
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost:8080;
location /static/ {
alias /var/www/akplanning-static/;
}
location / {
include /etc/nginx/uwsgi_params;
uwsgi_pass uwsgi://akplanning-server:3035;
}
}
}
```
### Initializing and migrating database
On the first start, the database must be initialized (the Tables created and so on).
When updating the project the database must be migrated.
Both are done using the `migrate` command.
This can be done manually by running the following command after the container has started:
`docker-compose exec -it akplanning-server ./manage.py migrate`
It can also be done automatically on each container start by setting `AUTO_MIGRATE_DB` to the string `true`
(as shown in the docker-compose file above).
Database migration may lead to the corruption or loss of data in some cases.
Make sure you have a backup before running the command and be very careful with enabling auto migration.
### Creating initial superuser
There are two ways to create the initial superuser when using the docker container.
For both the database must have been intialized before.
The first way is already shown in the docker-compose file above:
Using the environment variables `DJANGO_SUPERUSER_{USERNAME,EMAIL,PASSWORD}`.
The second way is to run the following command after the container has started:
`docker-compose exec -it akplanning-server ./manage.py createsuperuser`
### Extra django settings
For simple cases you can pass environment variables starting with `EXTRA_DJANGO_SETTING`.
The content of such variables is written into python files, which are loaded as settings.
For more complex scenarios you can also mount a docker volume to `/app/AKPlanning/settings` and add any number of python files to the volume.
## Updates
To update the setup to the current version on the main branch of the repository use the update
script ``Utils/update.sh`` or ``Utils/update.sh --prod`` in production.
Afterwards, you may check your setup by executing ``Utils/check.sh`` or ``Utils/check.sh --prod`` in production.
### Updating when using docker
To update when using docker, just switch the tag of the image for `akplanning-server`.
Then (if `AUTO_MIGRATE_DB` is not enabled), do a database migration as described in [Initializing and migrating database](#initializing-and-migrating-database)
GNU Affero General Public License
=================================
_Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
## Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: **(1)** assert copyright on the software, and **(2)** offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
## TERMS AND CONDITIONS
### 0. Definitions
“This License” refers to version 3 of the GNU Affero General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a “modified version” of the
earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based
on the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices”
to the extent that it includes a convenient and prominently visible
feature that **(1)** displays an appropriate copyright notice, and **(2)**
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code
The “source code” for a work means the preferred form of the work
for making modifications to it. “Object code” means any non-source
form of a work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other
than the work as a whole, that **(a)** is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and **(b)** serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
“Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
### 2. Basic Permissions
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
### 4. Conveying Verbatim Copies
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
### 5. Conveying Modified Source Versions
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified
it, and giving a relevant date.
* **b)** The work must carry prominent notices stating that it is
released under this License and any conditions added under section 7.
This requirement modifies the requirement in section 4 to
“keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
* **d)** If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
“aggregate” if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
### 6. Conveying Non-Source Forms
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either **(1)** a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or **(2)** access to copy the
Corresponding Source from a network server at no charge.
* **c)** Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
* **d)** Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A “User Product” is either **(1)** a “consumer product”, which means any
tangible personal property which is normally used for personal, family,
or household purposes, or **(2)** anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, “normally used” refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
### 7. Additional Terms
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or
authors of the material; or
* **e)** Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
### 8. Termination
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated **(a)**
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and **(b)** permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
### 11. Patents
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To “grant” such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either **(1)** cause the Corresponding Source to be so
available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. “Knowingly relying” means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is “discriminatory” if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license **(a)** in connection with copies of the covered work
conveyed by you (or copies made from those copies), or **(b)** primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
### 12. No Surrender of Others' Freedom
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
### 13. Remote Network Interaction; Use with the GNU General Public License
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License “or any later version” applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
_END OF TERMS AND CONDITIONS_
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a “Source” link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a “copyright disclaimer” for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.
......@@ -7,66 +7,28 @@ AKPlanning is a tool used for modeling, submitting, scheduling and displaying AK
It was built for KIF (German: Konferenz der deutschsprachigen Informatikfachschaften), refer to [the wiki](wiki.kif.rocks) for more Information.
## Setup
This repository contains a Django project with several apps.
### Requirements
AKPlanning has two types of requirements: System requirements are dependent on operating system and need to be installed manually beforehand. Python requirements will be installed inside a virtual environment (strongly recommended) during setup.
#### System Requirements
* Python 3.7
* Virtualenv
#### Python Requirements
Python requirements are listed in ``requirements.txt``. They can be installed with pip using ``-r requirements.txt``.
### Development Setup
* create a new directory that should contain the files in future, e.g. ``mkdir AKPlanning``
* change into that directory ``cd AKPlanning``
* clone this repository ``git clone URL .``
**Automatic Setup**
1. execute the setup bash script ``Utils/setup.sh``
**Manual Setup**
1. setup a virtual environment using the proper python version ``virtualenv env -p python3.7``
1. activate virtualenv ``source env/bin/activate``
1. install python requirements ``pip install -r requirements.txt``
1. setup necessary database tables etc. ``python manage.py migrate``
1. create a priviledged user, credentials are entered interactively on CLI ``python manage.py createsuperuser``
1. deactivate virtualenv ``deactivate``
## Structure
**Development Server**
This repository contains a Django project called AKPlanning. The functionality is encapsulated into Django apps:
To start the application for development use ``python manage.py runserver 0:8000`` from the root directory.
*Do not use this for deployment!*
1. **AKModel**: This app contains the general Django models used to represent events, users, rooms, scheduling constraints etc. This app is a basic requirements for the other apps. Data Import/Export also goes here.
1. **AKDashboard**: This app provides a landing page for the project. Per Event it provides links to all relevant functionalities and views.
1. **AKSubmission**: This app provides forms to submit all kinds of AKs, edit or delete them, as well as a list of all submitted AKs for an event.
1. **AKScheduling**: This app allows organizers to schedule AKs, i.e. assigning rooms, slots, etc. It marks conflicts of all modeled constraints and assists in creating a suitable schedule.
1. **AKPlan**: This app displays AKs and where/when they will take place for each event. Views are optimised according to usage/purpose.
In your browser, access ``http://127.0.0.1:8000/`` and continue from there.
## Setup instructions
### Updates
See [INSTALL.md](INSTALL.md) for detailed instructions on development and production setups.
To update the setup to the current version on the main branch of the repository use the update script ``Utils/update.sh`` or ``Utils/update.sh --prod`` in production.
Afterwards, you may check your setup by executing ``Utils/check.sh`` or ``Utils/check.sh --prod`` in production.
## Structure
This repository contains a Django project called AKPlanning. The functionality is encapsulated into Django apps:
1. AKModel: This app contains the general Django models used to represent events, users, rooms, scheduling constraints etc. This app is a basic requirements for the other apps.
## Developer Notes
* to regenerate translations use ````python manage.py makemessages -l de_DE --ignore venv````
* to create a data backup use ````python manage.py dumpdata --indent=2 > db.json --traceback````
* to export all database items belonging to a certain event use ````./Utils/json_export.sh <event_id> <export_prefix> [--prod]````. The results will be saved in ````backups/<export_prefix>.json````
......@@ -7,3 +7,4 @@ All scripts should be executed from the project folder (repository root).
* **setup** installation script for development setup
* **update** update script for development or production (--prod) setup
* **check** setup checking script for development and production (--prod) setup
* **json_export** export script for development and production (--prod) -- can be used to export all database items belonging to a given event
\ No newline at end of file
......@@ -4,18 +4,25 @@
# activate virtualenv when necessary
if [ -z ${VIRTUAL_ENV+x} ]; then
source env/bin/activate
source venv/bin/activate
fi
# enable really all warnings, some of them are silenced by default
if [[ "$@" == *"--all"* ]]; then
export PYTHONWARNINGS=all
fi
for arg in "$@"; do
if [[ "$arg" == "--all" ]]; then
export PYTHONWARNINGS=all
fi
done
# in case of checking production setup
if [[ "$@" == *"--prod"* ]]; then
export DJANGO_SETTINGS_MODULE=AKPlanning.settings_production
./manage.py check --deploy
fi
for arg in "$@"; do
if [[ "$arg" == "--prod" ]]; then
export DJANGO_SETTINGS_MODULE=AKPlanning.settings_production
./manage.py check --deploy
./manage.py makemigrations --dry-run --check
fi
done
# check the setup
./manage.py check
./manage.py makemigrations --dry-run --check
import json
import sys
event_id = int(sys.argv[1])
target_name = sys.argv[2]
print(f"Creating export for event '{event_id}' as '{target_name}'")
# Load json file just created by django
with open('backups/akplanning_only.json', 'r') as json_file:
exported_entries = json.load(json_file)
print(f"Loaded {len(exported_entries)} entries in total, restricting to event...")
entries_without_event = 0
entries_out = []
virtual_rooms_to_preserve = set()
# Loop over all dumped entries
for entry in exported_entries:
# Handle all entries with event reference
if "event" in entry['fields']:
event = int(entry['fields']['event'])
# Does this entry belong to the event we are looking for?
if event == event_id:
# Store for backup
entries_out.append(entry)
# Remember the primary keys of all rooms of this event
# Required for special handling of virtual rooms,
# since they inherit from normal rooms and have no direct event reference
if entry['model'] == "AKModel.room":
virtual_rooms_to_preserve.add(entry['pk'])
# Handle entries without event reference
else:
# Backup virtual rooms of that event
if entry['model'] == "AKOnline.virtualroom":
if entry['pk'] in virtual_rooms_to_preserve:
entries_out.append(entry)
# Backup the event itself
elif entry['model'] == "AKModel.event":
if int(entry['pk']) == event_id:
entries_out.append(entry)
else:
# This should normally not happen (all other models should have a reference to the event)
entries_without_event += 1
print(entry)
print(f"Ignored entries without event: {entries_without_event}")
print(f"Exporting {len(entries_out)} entries for event")
with open(f'backups/{target_name}.json', 'w') as json_file:
json.dump(entries_out, json_file, indent=2)
#!/usr/bin/env bash
# Update AKPlanning
# execute as Utils/update.sh id_to_export target_name_to_export_to [--prod]
# abort on error, print executed commands
set -ex
# activate virtualenv if necessary
if [ -z ${VIRTUAL_ENV+x} ]; then
source venv/bin/activate
fi
# set environment variable when we want to update in production
if [ "$3" = "--prod" ]; then
export DJANGO_SETTINGS_MODULE=AKPlanning.settings_production
fi
mkdir -p ../backups/
python manage.py dumpdata AKDashboard AKModel AKOnline AKPlan AKScheduling AKSubmission --indent=2 > "backups/akplanning_only.json" --traceback
python ./Utils/json_export.py $1 $2
rm backups/akplanning_only.json
#!/usr/bin/env bash
# Setup AKPlanning
# execute as Utils/check.sh
# execute as Utils/setup.sh
# abort on error, print executed commands
set -ex
# remove old virtualenv
rm -rf env/
rm -rf venv/
# Setup Python Environment
# Requires: Virtualenv, appropriate Python installation
virtualenv env -p python3.7
source env/bin/activate
virtualenv venv -p python3.11
source venv/bin/activate
pip install --upgrade setuptools pip wheel
pip install -r requirements.txt
# set environment variable when we want to update in production
if [ "$1" = "--prod" ]; then
export DJANGO_SETTINGS_MODULE=AKPlanning.settings_production
fi
if [ "$1" = "--ci" ]; then
export DJANGO_SETTINGS_MODULE=AKPlanning.settings_ci
fi
# Setup database
python manage.py migrate
# Prepare static files and translations
python manage.py collectstatic --noinput
python manage.py compilemessages -l de_DE
# Create superuser
# Credentials are entered interactively on CLI
python manage.py createsuperuser
# Generate documentation (but not for CI use)
if [ -n "$1" = "--ci" ]; then
cd docs
make html
cd ..
fi
deactivate
#!/usr/bin/env bash
# Test the AKPlanning setup
# execute as Utils/test.sh
# activate virtualenv when necessary
if [ -z ${VIRTUAL_ENV+x} ]; then
source venv/bin/activate
fi
# enable really all warnings, some of them are silenced by default
for arg in "$@"; do
if [[ "$arg" == "--all" ]]; then
export PYTHONWARNINGS=all
fi
done
# in case of checking production setup
for arg in "$@"; do
if [[ "$arg" == "--prod" ]]; then
export DJANGO_SETTINGS_MODULE=AKPlanning.settings_production
./manage.py test --deploy
fi
done
# run tests
./manage.py test
#!/usr/bin/env bash
# Update AKPlanning
# execute as Utils/check.sh
# execute as Utils/update.sh
# abort on error, print executed commands
set -ex
# activate virtualenv if necessary
if [ -z ${VIRTUAL_ENV+x} ]; then
source env/bin/activate
source venv/bin/activate
fi
# set environment variable when we want to update in production
......@@ -15,13 +15,22 @@ if [ "$1" = "--prod" ]; then
export DJANGO_SETTINGS_MODULE=AKPlanning.settings_production
fi
# before potentially breaking anything, create a data backup
mkdir -p backups/
python manage.py dumpdata --indent=2 > "backups/$(date +"%Y%m%d%H%M")_datadump.json" --traceback
git pull
pip install --upgrade setuptools pip wheel
pip install --upgrade -r requirements.txt
if [ "$1" = "--prod" ]; then
./manage.py collectstatic --noinput
fi
./manage.py migrate
./manage.py collectstatic --noinput
./manage.py compilemessages -l de_DE
# Update documentation
cd docs
make html
cd ..
touch AKPlanning/wsgi.py
<VirtualHost *:80>
ServerName $SUBDOMAIN
ServerAdmin $MAILADDRESS
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /static /srv/AKPlanning/static
<Directory /srv/AKPlanning/static>
Require all granted
</Directory>
ProxyPassMatch ^/static/ !
ProxyPass / uwsgi://127.0.0.1:3035/
RewriteEngine on
RewriteCond %{SERVER_NAME} =$SUBDOMAIN
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName $SUBDOMAIN
ServerAdmin $MAILADDRESS
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /static /srv/AKPlanning/static
<Directory /srv/AKPlanning/static>
Require all granted
</Directory>
ProxyPassMatch ^/static/ !
ProxyPass / uwsgi://127.0.0.1:3035/
ProxyPassReverse / uwsgi://127.0.0.1:3035/
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile $PATHTOfullchain.pem
SSLCertificateKeyFile $PATHTOprivkey.pem
</VirtualHost>
</IfModule>