Skip to content
This repository has been archived by the owner on Feb 12, 2022. It is now read-only.

Revert "Revert "Ophase Categories"" #135

Merged
merged 4 commits into from
Feb 10, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions clothing/tests/tests_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,7 @@ def test_color_cannot_create_two_identical_types(self):

class OrderModelTest(TestCase):
def setUp(self):
self.ophase = Ophase.objects.create(
start_date=date(2014, 4, 7), end_date=date(2014, 4, 11), is_active=True)
self.ophase = Ophase.objects.create(name="Testophase", is_active=True)
self.person = Person.objects.create(ophase=self.ophase, prename="John", name="Doe", email="[email protected]",
phone="12345", matriculated_since="WS42", degree_course="Bsc", experience_ophase="nein", why_participate="Gründe")

Expand Down
27 changes: 27 additions & 0 deletions exam/migrations/0003_auto_20170209_2025.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-09 19:25
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('ophasebase', '0004_auto_20170209_2025'),
('exam', '0002_auto_20150916_1444'),
]

operations = [
migrations.RemoveField(
model_name='assignment',
name='group_category',
),
migrations.AddField(
model_name='assignment',
name='group_category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ophasebase.OphaseCategory',
verbose_name='Gruppenkategorie', null=True, blank=False),
),
]
5 changes: 2 additions & 3 deletions exam/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
from django.utils import formats
from django.utils.translation import ugettext_lazy as _

from ophasebase.models import Ophase
from staff.models import GroupCategory
from ophasebase.models import Ophase, OphaseCategory
from students.models import Student


Expand Down Expand Up @@ -54,7 +53,7 @@ class Meta:

ophase = models.ForeignKey(Ophase, models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
group_category = models.ForeignKey(GroupCategory, models.CASCADE, verbose_name=_('Gruppenkategorie'))
group_category = models.ForeignKey(OphaseCategory, models.CASCADE, verbose_name=_('Gruppenkategorie'))
spacing = models.PositiveSmallIntegerField(choices=SPACING_CHOICES, default=2, verbose_name=_('Sitzplatzabstand'))
mode = models.PositiveSmallIntegerField(choices=MODE_CHOICES, default=0, verbose_name=_('Verteilmodus'))
count = models.PositiveIntegerField(verbose_name=_('# Zuteilungen'))
Expand Down
15 changes: 13 additions & 2 deletions ophasebase/admin.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _

from .models import Building, Ophase, Room
from .models import Building, Ophase, Room, OphaseCategory, OphaseActiveCategory


@admin.register(Ophase)
class OphaseAdmin(admin.ModelAdmin):
list_display = ('get_name', 'start_date', 'end_date', 'is_active')
list_display = ('name', 'start_date', 'end_date', 'is_active')


@admin.register(Building)
Expand All @@ -25,3 +25,14 @@ class RoomAdmin(admin.ModelAdmin):
(_('Ausstattung'), {'fields': ['type', 'capacity', 'has_beamer']}),
(_('Position'), {'fields': ['lat', 'lng']})
]


@admin.register(OphaseCategory)
class OphaseCategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'priority')


@admin.register(OphaseActiveCategory)
class OphaseActiveCategory(admin.ModelAdmin):
list_display = ('ophase', 'category', 'start_date', 'end_date')
list_display_links = ('ophase', 'category')
2 changes: 1 addition & 1 deletion ophasebase/fixtures/ophasebase.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[{"model": "ophasebase.building", "pk": 1, "fields": {"area": "S", "subarea": 2, "number": 2, "label": "Piloty", "remarks": ""}}, {"model": "ophasebase.room", "pk": 1, "fields": {"building": 1, "number": "A126", "type": "SR", "has_beamer": true, "capacity": 15, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.room", "pk": 2, "fields": {"building": 1, "number": "A213", "type": "SR", "has_beamer": true, "capacity": 15, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.room", "pk": 3, "fields": {"building": 1, "number": "C110", "type": "HS", "has_beamer": true, "capacity": 80, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.room", "pk": 4, "fields": {"building": 1, "number": "C120", "type": "HS", "has_beamer": true, "capacity": 80, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.ophase", "pk": 1, "fields": {"start_date": "2016-04-03", "end_date": "2016-04-07", "is_active": true}}]
[{"model": "ophasebase.building", "pk": 1, "fields": {"area": "S", "subarea": 2, "number": 2, "label": "Piloty", "remarks": ""}}, {"model": "ophasebase.room", "pk": 1, "fields": {"building": 1, "number": "A126", "type": "SR", "has_beamer": true, "capacity": 15, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.room", "pk": 2, "fields": {"building": 1, "number": "A213", "type": "SR", "has_beamer": true, "capacity": 15, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.room", "pk": 3, "fields": {"building": 1, "number": "C110", "type": "HS", "has_beamer": true, "capacity": 80, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.room", "pk": 4, "fields": {"building": 1, "number": "C120", "type": "HS", "has_beamer": true, "capacity": 80, "lat": 0.0, "lng": 0.0}}, {"model": "ophasebase.ophase", "pk": 1, "fields": {"name": "Testophase", "is_active": true}}]
74 changes: 74 additions & 0 deletions ophasebase/migrations/0004_auto_20170209_2025.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-09 19:25
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('ophasebase', '0003_auto_20160825_1424'),
('students', '0003_auto_20150913_1509'),
]

operations = [
migrations.CreateModel(
name='OphaseActiveCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start_date', models.DateField(verbose_name='Beginn')),
('end_date', models.DateField(verbose_name='Ende')),
],
options={
'ordering': ['ophase', 'category'],
'verbose_name': 'Aktive Kategorie einer Ophase',
'verbose_name_plural': 'Aktive Katgegorien einer Ophase',
},
),
migrations.CreateModel(
name='OphaseCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Name')),
('description_template', models.CharField(max_length=50, verbose_name='Beschreibung in Template')),
('lang', models.CharField(default='de', max_length=5, verbose_name='Sprachcode')),
('priority', models.PositiveIntegerField(help_text='Die Priorität bestimmt unter anderem die Reihenfolge der Anzeige auf der Webseite', verbose_name='Priorität')),
],
options={
'ordering': ['priority'],
'verbose_name': 'Art der Ophase',
'verbose_name_plural': 'Arten der Ophase',
},
),
migrations.RemoveField(
model_name='ophase',
name='end_date',
),
migrations.RemoveField(
model_name='ophase',
name='start_date',
),
migrations.AddField(
model_name='ophase',
name='name',
field=models.CharField(default='Ophase', max_length=100),
preserve_default=False,
),
migrations.AddField(
model_name='ophaseactivecategory',
name='category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ophasebase.OphaseCategory', verbose_name='Art der Ophase'),
),
migrations.AddField(
model_name='ophaseactivecategory',
name='ophase',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ophasebase.Ophase', verbose_name='Ophase'),
),
migrations.AddField(
model_name='ophase',
name='categories',
field=models.ManyToManyField(related_name='ophase_categories', through='ophasebase.OphaseActiveCategory', to='ophasebase.OphaseCategory'),
),
]
81 changes: 69 additions & 12 deletions ophasebase/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import formats
from django.utils.datetime_safe import datetime
from django.utils.translation import ugettext_lazy as _


Expand Down Expand Up @@ -72,23 +73,25 @@ class Meta:
verbose_name = _('Ophase')
verbose_name_plural = _('Ophasen')

start_date = models.DateField(verbose_name=_('Beginn'))
end_date = models.DateField(verbose_name=_('Ende'))
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=False, verbose_name=_('Aktiv?'))
contact_email_address = models.EmailField(verbose_name=_('Kontaktadresse Leitung'))
categories = models.ManyToManyField("OphaseCategory", through="OphaseActiveCategory", related_name=u'ophase_categories')

def get_name(self):
term = _('Ophase')
if self.start_date.month == 4:
term = _('Sommerophase')
elif self.start_date.month == 10:
term = _('Winterophase')
return "%s %d" % (term, self.start_date.year)
def __str__(self):
return self.name

get_name.short_description = _('Ophase')
@property
def start_date(self):
if self.ophaseactivecategory_set.count() == 0:
return datetime.now()
return min(c.start_date for c in self.ophaseactivecategory_set.all())

def __str__(self):
return self.get_name()
@property
def end_date(self):
if self.ophaseactivecategory_set.count() == 0:
return datetime.now()
return max(c.end_date for c in self.ophaseactivecategory_set.all())

def get_semester(self):
term = _('Jahr')
Expand Down Expand Up @@ -137,3 +140,57 @@ def current():
return Ophase.objects.get(is_active=True)
except Ophase.DoesNotExist:
return None


class OphaseCategory(models.Model):
"""Object representing the category of an Ophase"""
class Meta:
verbose_name = _('Art der Ophase')
verbose_name_plural = _('Arten der Ophase')
ordering = ['priority']

name = models.CharField(max_length=100, verbose_name=_('Name'))
description_template = models.CharField(max_length=50, verbose_name=_('Beschreibung in Template'))
lang = models.CharField(max_length=5, verbose_name=_('Sprachcode'), default="de")
priority = models.PositiveIntegerField(verbose_name=_("Priorität"), help_text=_("Die Priorität bestimmt unter anderem die Reihenfolge der Anzeige auf der Webseite"))

def __str__(self):
return self.name


class OphaseActiveCategory(models.Model):
"""An active category of a given Ophase"""
class Meta:
verbose_name = _('Aktive Kategorie einer Ophase')
verbose_name_plural = _('Aktive Katgegorien einer Ophase')
ordering = ['ophase', 'category']

ophase = models.ForeignKey(Ophase, verbose_name=_('Ophase'), on_delete=models.CASCADE)
category = models.ForeignKey(OphaseCategory, verbose_name=_('Art der Ophase'), on_delete=models.CASCADE)
start_date = models.DateField(verbose_name=_('Beginn'))
end_date = models.DateField(verbose_name=_('Ende'))

def get_human_duration(self):
"""
Returns the start_date and end_date of the ophase as human readable
e.g. vom 3. April 2014 bis 6. April 2016
"""
return _('vom %(begin)s bis %(end)s') % {
'begin': formats.date_format(self.start_date, 'DATE_FORMAT'),
'end': formats.date_format(self.end_date, 'DATE_FORMAT'),}

def get_human_short_duration(self):
"""
Returns the start_date and end_date of the ophase category as
human readable e.g. 3. - 6. April
"""
beginformat = 'j. '
if self.start_date.month != self.end_date.month:
beginformat +='F'
endformat = 'j. F'
return '%(begin)s - %(end)s' % {
'begin': formats.date_format(self.start_date, beginformat),
'end': formats.date_format(self.end_date, endformat),}

def __str__(self):
return "{}: {}".format(self.ophase, self.category)
18 changes: 2 additions & 16 deletions ophasebase/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ class OphaseIsActive(TestCase):

def test_only_one_is_active(self):
# create Ophase - should be active
o1 = Ophase.objects.create(start_date=date(2014, 4, 7), end_date=date(2014, 4, 11), is_active=True)
o1 = Ophase.objects.create(name="Testophase 1", is_active=True)
self.assertEqual(o1.is_active, True)
# now create other Ophase - should be active while first one should be inactive
o2 = Ophase.objects.create(start_date=date(2014, 10, 6), end_date=date(2014, 10, 10), is_active=True)
o2 = Ophase.objects.create(name="Testophase 2", is_active=True)
o1 = Ophase.objects.get(pk=o1.pk)
self.assertEqual(o1.is_active, False)
self.assertEqual(o2.is_active, True)
Expand All @@ -27,17 +27,3 @@ def test_only_one_is_active(self):
o2 = Ophase.objects.get(pk=o2.pk)
self.assertEqual(o1.is_active, True)
self.assertEqual(o2.is_active, False)

class OphaseBeginBeforeEnd(TestCase):
"""Ensure that an Ophase does not end before it begins."""

def test_fail_on_wrong(self):
o = Ophase.objects.create(start_date=date(2014, 4, 8), end_date=date(2014, 4, 1))
self.assertRaises(ValidationError, o.clean)

def test_pass_on_right(self):
try:
o = Ophase.objects.create(start_date=date(2014, 4, 1), end_date=date(2014, 4, 5))
o.clean()
except ValidationError:
self.fail("Creation of Ophase raised ValidationError unexpectedly.")
9 changes: 4 additions & 5 deletions staff/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.utils.html import format_html
from django.utils.translation import ugettext as _

from ophasebase.models import OphaseCategory
from .admin_actions import (
helper_job_overview,
mail_export,
Expand All @@ -16,7 +17,6 @@
update_attendees, mark_attendance_x, mark_attendance_a, mark_attendance_e, mark_phoned_x, mark_phoned_e,
mark_phoned_n, mark_attendance_v, generate_orga_cert)
from .models import (
GroupCategory,
HelperJob,
OrgaJob,
Person,
Expand All @@ -30,7 +30,6 @@

@admin.register(OrgaJob)
@admin.register(HelperJob)
@admin.register(GroupCategory)
class LabelSortAdmin(admin.ModelAdmin):
"""Simple ModelAdmin which just shows the field Value in the list view"""
list_display = ['label']
Expand All @@ -42,8 +41,8 @@ class TutorFilter(admin.SimpleListFilter):

def lookups(self, request, model_admin):
choices = [('onlytutors', _('Alle Tutoren'))]
for gc in GroupCategory.objects.all():
choices.append((gc.id, gc.label))
for gc in OphaseCategory.objects.all():
choices.append((gc.id, gc.name))
choices.append(('notutors', _('Keine Tutoren')))
return choices

Expand Down Expand Up @@ -96,7 +95,7 @@ def is_tutor_with_title(self, obj):
if obj.is_tutor == True and obj.tutor_for is not None:
icon_url = static('admin/img/icon-yes.svg')
return format_html('<img src="{}" alt="{}" title="{}" />',
icon_url, obj.is_tutor, obj.tutor_for.label)
icon_url, obj.is_tutor, obj.tutor_for.name)
else:
return _boolean_icon(obj.is_tutor)

Expand Down
6 changes: 3 additions & 3 deletions staff/dashboard_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

from ophasebase.models import Ophase

from .models import GroupCategory, Person, TutorGroup
from .models import Person, TutorGroup


class GroupMassCreateForm(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
category_choices = [(gc.id, str(gc)) for gc in GroupCategory.objects.all()]
category_choices = [(gc.id, str(gc)) for gc in Ophase.current().categories.all()]
self.fields['category'] = forms.ChoiceField(label=_('Gruppenkategorie'), choices=category_choices)
self.fields['group_names'] = forms.CharField(label=_('Gruppennamen'), help_text=_('Einen Gruppennamen pro Zeile eintragen.'), widget=forms.Textarea)

Expand All @@ -24,7 +24,7 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
current_ophase = Ophase.current()

group_categories = GroupCategory.objects.all()
group_categories = Ophase.current().categories.all()
group_category_choices = [(gc.id, str(gc)) for gc in group_categories]
self.fields['category'] = forms.ChoiceField(label=_('Gruppenkategorie'), choices=group_category_choices)

Expand Down
6 changes: 3 additions & 3 deletions staff/dashboard_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
from django.views.generic import FormView, TemplateView, ListView, DetailView

from dashboard.components import DashboardAppMixin
from ophasebase.models import Ophase
from ophasebase.models import Ophase, OphaseCategory
from .dashboard_forms import GroupMassCreateForm, TutorPairingForm
from .models import GroupCategory, Person, TutorGroup, AttendanceEvent
from .models import Person, TutorGroup, AttendanceEvent


class StaffAppMixin(DashboardAppMixin):
Expand Down Expand Up @@ -38,7 +38,7 @@ def form_valid(self, form):
context['ophase'] = False
else:
context['ophase'] = True
category = GroupCategory.objects.get(id=form.cleaned_data['category'])
category = OphaseCategory.objects.get(id=form.cleaned_data['category'])
existing_group_names = set(group.name for group in TutorGroup.objects.filter(ophase=current_ophase))
new_groups = []
context['duplicate_group_count'] = 0
Expand Down
Loading