views.py 7.81 KB
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django_datatables_view.base_datatable_view import BaseDatatableView

import settings
from common.decorators import render, ajax
from normalization import normalize
from webapp.forms import EditMeaningForm
from webapp.models import Domain, Entry, Expression, Meaning, MeaningStatus, Source


@login_required
@render()
def preview_page(request):
    js_vars = {
        'ajax_expressions': reverse('expressions'),
        'ajax_meanings_info': reverse('expression_info'),
        'ajax_refresh_meanings': reverse('expression_info_by_meaning'),
        'ajax_edit_meaning_form': reverse('edit_meaning_form'),
        'ajax_meaning_form_submit': reverse('meaning_form_submit')
    }
    return {'js_vars': js_vars}


@login_required
@render()
def edit_page(request):
    js_vars = {
        'ajax_expressions': reverse('edit_table'),
        'ajax_meanings_info': reverse('meaning_info_by_expression'),
        'ajax_refresh_meanings': reverse('meaning_info_by_meaning'),
        'ajax_edit_meaning_form': reverse('edit_meaning_form'),
        'ajax_meaning_form_submit': reverse('meaning_form_submit')
    }
    return {'js_vars': js_vars}


@csrf_exempt
@render('expression_info.html')
@ajax(method='get', encode_result=False)
def expression_info(request, id):
    entry = Entry.objects.get(id=id)
    # sel_expr = Expression.objects.get(id=id)
    # top_expressions = Expression.objects.filter(is_catchword=True, text=sel_expr.text)
    # top_meanings = [expr.meaning for expr in top_expressions]

    meanings = []
    for meaning in entry.meanings.all():
        gen_expressions = []
        if not settings.NKJP_VALIDATION:
            gen_expressions = normalize.expressions(meaning.expressions.all())
        meanings.append({'meaning': meaning,
                         'orig_expressions': meaning.expressions.all(),
                         'gen_expressions': gen_expressions})

    return {'meanings': meanings}


@csrf_exempt
@render('expression_info.html')
@ajax(method='get', encode_result=False)
def expression_info_by_meaning(request, id):
    meaning = Meaning.objects.get(id=id)
    sel_expr = meaning.expressions.filter(is_catchword=True)[0]
    top_expressions = Expression.objects.filter(is_catchword=True, text=sel_expr.text)
    top_meanings = [expr.meaning for expr in top_expressions]

    meanings = []
    for meaning in top_meanings:
        gen_expressions = []
        if not settings.NKJP_VALIDATION:
            gen_expressions = normalize.expressions(meaning.expressions.all())
        meanings.append({'meaning': meaning,
                         'orig_expressions': meaning.expressions.all(),
                         'gen_expressions': gen_expressions})

    return {'meanings': meanings}


@csrf_exempt
@render('expression_info.html')
@ajax(method='get', encode_result=False)
def meaning_info_by_expression(request, id):
    sel_expr = Expression.objects.get(id=id)

    top_meanings = [sel_expr.meaning]
    meanings = []
    for meaning in top_meanings:
        gen_expressions = []
        if not settings.NKJP_VALIDATION:
            gen_expressions = normalize.expressions(meaning.expressions.all())
        meanings.append({'meaning': meaning,
                         'orig_expressions': meaning.expressions.all(),
                         'gen_expressions': gen_expressions})

    return {'meanings': meanings}


@csrf_exempt
@render('expression_info.html')
@ajax(method='get', encode_result=False)
def meaning_info_by_meaning(request, id):
    meaning = Meaning.objects.get(id=id)

    top_meanings = [meaning]
    meanings = []
    for meaning in top_meanings:
        gen_expressions = []
        if not settings.NKJP_VALIDATION:
            gen_expressions = normalize.expressions(meaning.expressions.all())
        meanings.append({'meaning': meaning,
                         'orig_expressions': meaning.expressions.all(),
                         'gen_expressions': gen_expressions})

    return {'meanings': meanings}


@csrf_exempt
@render('edit_meaning_form.html')
@ajax(method='get', encode_result=False)
def edit_meaning_form(request, id):
    meaning = Meaning.objects.get(id=id)
    form = EditMeaningForm(instance=meaning)
    return {'form': form, 'id': id}


@csrf_exempt
@ajax(method='post', encode_result=False)
def meaning_form_submit(request):
    meaning = Meaning.objects.get(id=request.POST['id'])
    status = MeaningStatus.objects.get(pk=request.POST['status'])
    comment = request.POST['comment']

    meaning.status = status
    meaning.comment = comment
    meaning.save()

    return HttpResponse(status=200)


class ExpressionsJson(BaseDatatableView):
    model = Entry
    columns = ['name', 'sources', 'domains', 'id']
    order_columns = ['name', 'sources', 'domains']
    max_display_length = 100

    def get_initial_queryset(self):
        return Entry.objects.none()

    def render_column(self, row, column):
        if column == 'name':
            return u'{0}'.format(row.name)
        elif column == 'sources':
            return u'{0}'.format(', '.join(['<a href="%s">%s</a>' % (source.url, source.name)
                                           for source in row.sources.order_by('name')]))
        elif column == 'domains':
            return u'{0}'.format('; '.join([domain.name for domain in row.domains.order_by('name')]))
        else:
            return super(ExpressionsJson, self).render_column(row, column)

    def filter_queryset(self, qs):

        search = self.request.GET.get(u'search[value]', None)
        if search:
            qs = Entry.objects.filter(name__startswith=search.upper())

        source = self.request.GET.get(u'columns[1][search][value]', None)
        if search and source:
            qs = qs.filter(sources__name__istartswith=source)

        domain = self.request.GET.get(u'columns[2][search][value]', None)
        if search and domain:
            qs = qs.filter(domains__name__istartswith=domain)

        return qs


class EditTableJson(BaseDatatableView):
    model = Expression
    columns = ['text', 'sources', 'domain', 'status', 'id']
    order_columns = ['text', 'sources', 'meaning__domain', 'meaning__status']
    max_display_length = 100

    def get_initial_queryset(self):
        return Expression.objects.filter(is_catchword=True).exclude(meaning__status=None).exclude(meaning__status__key='ok')

    def render_column(self, row, column):
        if column == 'text':
            return u'{0}'.format(row.text)
        elif column == 'sources':
            sources = Source.objects.filter(links__expression__in=row.meaning.expressions.all()).distinct()
            return u'{0}'.format(', '.join('<a href="%s">%s</a>' % (source.url, source.name)
                                           for source in sources.all()))
        elif column == 'domain':
            domains = row.meaning.domains.all()
            return u'{0}'.format('; '.join([domain.name for domain in domains.all()]))
        elif column == 'status':
            return u'{0}'.format(row.meaning.status.name)
        else:
            return super(EditTableJson, self).render_column(row, column)

    def filter_queryset(self, qs):

        search = self.request.GET.get(u'search[value]', None)
        if search:
            qs = qs.filter(text__startswith=search.upper())

        source = self.request.GET.get(u'columns[1][search][value]', None)
        if source:
            qs = qs.filter(link__source__name__istartswith=source)

        domain = self.request.GET.get(u'columns[2][search][value]', None)
        if domain:
            qs = qs.filter(meaning__domains__name__istartswith=domain)

        status = self.request.GET.get(u'columns[3][search][value]', None)
        if status:
            qs = qs.filter(meaning__status__name=status)

        return qs.distinct()