views.py 7.54 KB
# -*- coding: utf-8 -*-

from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from common.decorators import render
from common.models import FlatPage
from common.util import make_form
from management.forms import AddClassificationForm, AddClassificationValueForm, \
    AddExclusionClassForm, ExclusionClassForm, AddQualifierForm, ChangeClassForm, \
    VocabularyForm, TemplateChoiceForm, FlatPageForm
from dictionary.models import Vocabulary, managed_vocabularies, \
    ClassificationValue, Classification, Qualifier, QualifierExclusionClass, \
    MultilingualText, TranslatedText


@login_required
@render()
def management_menu(request):
    return {}


@permission_required('dictionary.manage_vocabulary')
@render()
def manager_view(request):
    to_return = {
        'users': User.objects.order_by('username'),
        'vocabularies_info': [
            (
                v, request.user in v.all_managers(),
                v.all_viewers(), v.all_editors(), v.all_managers()
            )
            for v in Vocabulary.objects.order_by('id')],
        'js_vars': {
            'ajax_add_vocabulary': reverse('add_vocabulary'),
            # 'ajax_get_permissions': reverse('vocabulary_permissions'),
            'ajax_set_permission': reverse('set_vocabulary_permission'),
        },
    }
    return to_return


@permission_required('dictionary.manage_vocabulary')
@render()
def manage_classifications(request):
    to_return = {}
    add_form = make_form(request, AddClassificationForm)
    if add_form.is_valid():
        add_form.save()
    to_return['add_form'] = add_form
    if request.POST.get('det') == 'value_form':
        add_form = AddClassificationValueForm(data=request.POST)
        if add_form.is_valid():
            add_form.save()
    if request.POST.get('det') == 'vocabulary_form':
        form = VocabularyForm(
            data=request.POST, queryset=managed_vocabularies(request.user))
        if form.is_valid():
            c = form.cleaned_data['classification']
            v = form.cleaned_data['vocabulary']
            c.vocabularies.add(v)  # add
    if request.POST.get('det') == 'value_remove':
        pk = int(request.POST['id'])
        try:
            cv = ClassificationValue.objects.get(pk=pk)
            cv.deleted = True
            cv.save()
        except ClassificationValue.DoesNotExist:
            pass
    if request.POST.get('det') == 'value_rename':
        pk = int(request.POST['id'])
        label = request.POST['new_name']
        try:
            v = ClassificationValue.objects.get(pk=pk)
            v.label = label
            v.save()
        except ClassificationValue.DoesNotExist:
            pass
    if request.POST:
        return HttpResponseRedirect(reverse('manage_classifications'))

    classification_forms = []
    for c in Classification.objects.all():
        value_form = AddClassificationValueForm(classification=c)
        vocabs = managed_vocabularies(request.user)
        using = c.vocabularies.all() & vocabs
        other = vocabs.exclude(pk__in=using.values_list('pk', flat=True))
        vocab_form = VocabularyForm(classification=c, queryset=other)
        classification_forms.append((c, value_form, vocab_form, using))
    to_return['classification_forms'] = classification_forms
    return to_return


@permission_required('dictionary.manage_vocabulary')
@render()
def manage_qualifiers(request):
    det = request.POST.get('det')
    if det == 'add_exclusion_class':
        form = AddExclusionClassForm(data=request.POST)
        if form.is_valid():
            form.save()
    if det == 'remove_exclusion_class':
        form = ExclusionClassForm(data=request.POST)
        if form.is_valid():
            ec = form.cleaned_data['ec']
            ec.delete()
    if det == 'add_qualifier':
        form = AddQualifierForm(data=request.POST)
        if form.is_valid():
            form.save()
    prefix = q = None
    for name, _value in request.POST.iteritems():
        if name.startswith('cec'):
            prefix = name.split('-')[0]
            q = Qualifier.objects.get(pk=int(prefix[3:]))
            break
    if prefix:
        form = ChangeClassForm(data=request.POST, instance=q, prefix=prefix)
        if form.is_valid():
            form.save()
    if det == 'remove_qualifier':
        pk = int(request.POST['id'])
        try:
            q = Qualifier.objects.get(pk=pk)
            q.deleted = True
            q.save()
        except Qualifier.DoesNotExist:
            pass
    if request.POST:
        return HttpResponseRedirect(reverse('manage_qualifiers'))

    to_return = {}
    form_list = []
    for vocabulary in managed_vocabularies(request.user):
        add_exclusion_class_form = AddExclusionClassForm(vocabulary=vocabulary)
        empty_ec = QualifierExclusionClass.objects.filter(
            vocabulary=vocabulary).extra(where=[
                'not exists (select * from kwalifikatory '
                'where klasa = klasy_wykluczania.id)'])
        if empty_ec:
            remove_exclusion_class_form = ExclusionClassForm(queryset=empty_ec)
        else:
            remove_exclusion_class_form = None
        add_qualifier_form = AddQualifierForm(vocabulary=vocabulary)
        qualifiers = Qualifier.objects.filter(vocabulary=vocabulary)
        qualifier_forms = []
        for q in qualifiers:
            change_class_form = ChangeClassForm(
                instance=q, prefix='cec%s' % q.pk)
            qualifier_forms.append((q, change_class_form))
        form_list.append((
            vocabulary.id, add_exclusion_class_form,
            remove_exclusion_class_form,
            add_qualifier_form, qualifier_forms
        ))
    to_return['form_list'] = form_list
    return to_return


@permission_required('dictionary.manage_vocabulary')
@render('table_view.html')
def table_view(request):
    js_vars = {
        'ajax_load_template': reverse('table_edit_form'),
        'ajax_template_row': reverse('new_template_row'),
        'ajax_preview_form': reverse('template_preview_form'),
        'ajax_load_preview': reverse('template_preview'),
        'ajax_save_template': reverse('save_template'),
    }
    return {'form': TemplateChoiceForm(), 'js_vars': js_vars}


@permission_required('dictionary.manage_vocabulary')
@render('multilingual_texts.html')
def multilingual_texts(request):
    if request.POST:
        for key, value in request.POST.iteritems():
            if key.startswith('tr-'):
                tr_id = int(key[len('tr-'):])
                tr = TranslatedText.objects.get(id=tr_id)
                tr.text = value
                tr.save()
        return HttpResponseRedirect(reverse('multilingual_texts'))
    multi_texts = MultilingualText.objects.all()
    for mt in multi_texts:
        mt.add_translated_texts()
    return {'multi_texts': multi_texts}


@permission_required('dictionary.manage_vocabulary')
@render('flat_pages.html')
def flat_pages(request):
    return {'pages': FlatPage.objects.all()}


@permission_required('dictionary.manage_vocabulary')
@render('flat_page_edit.html')
def flat_page_edit(request, text_id):
    page = get_object_or_404(FlatPage, text_id=text_id)
    if request.POST:
        page_form = FlatPageForm(request.POST, instance=page)
        if page_form.is_valid():
            page_form.save()
            return HttpResponseRedirect(
                reverse('flat_page_edit', args=[text_id]))
    else:
        page_form = FlatPageForm(instance=page)
    return {'page_form': page_form}