<commit_before># coding=utf-8

from django import forms
from django.conf import settings
from django.views.decorators.http import require_safe
from django.contrib import auth
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.shortcuts import render_to_response
from formtools.wizard.views import SessionWizardView
from feedback.models import Veranstaltung
from feedback.forms import VeranstaltungEvaluationForm, VeranstaltungBasisdatenForm, VeranstaltungPrimaerDozentForm, \
    VeranstaltungDozentDatenForm, VeranstaltungFreieFragen, VeranstaltungTutorenForm
from django.core.mail import send_mail


@require_safe
def login(request):
    if 'vid' in request.GET and 'token' in request.GET:
        vid = int(request.GET['vid'])
        token = unicode(request.GET['token'])

        user = auth.authenticate(vid=vid, token=token)
        if user:
            auth.login(request, user)
            v = Veranstaltung.objects.get(id=vid)
            request.session['vid'] = v.id
            request.session['veranstaltung'] = unicode(v)

            if v.status == Veranstaltung.STATUS_BESTELLUNG_LIEGT_VOR or \
                    v.status == Veranstaltung.STATUS_BESTELLUNG_GEOEFFNET:
                return HttpResponseRedirect(reverse('veranstalter-index'))

    return render(request, 'veranstalter/login_failed.html')


VERANSTALTER_VIEW_TEMPLATES = {
    "evaluation": "formtools/wizard/evaluation.html",
    "basisdaten": "formtools/wizard/basisdaten.html",
    "primaerdozent": "formtools/wizard/primaerdozent.html",
    "verantwortlicher_address": "formtools/wizard/address.html",
    "freie_fragen": "formtools/wizard/freiefragen.html",
    "tutoren": "formtools/wizard/tutoren.html",
    "zusammenfassung": "formtools/wizard/zusammenfassung.html"
}


def perform_evalution(wizard):
    """
    Wenn wir keine Vollerhebung haben, und der Veranstalter nicht evauliert, dann
    springt der Wizard direkt zur Zusammenfassung.
    """
    cleaned_data = wizard.get_cleaned_data_for_step('evaluation') or {}
    v = Veranstaltung.objects.get(id=wizard.request.session['vid'])

    if v.semester.vollerhebung:
        return True

    return cleaned_data.get('evaluieren', True)


def show_primaerdozent_form(wizard):
    show_summary_form = perform_evalution(wizard)
    if show_summary_form:
        cleaned_data = wizard.get_cleaned_data_for_step('basisdaten') or {}
        ergebnis_empfaenger = cleaned_data.get('ergebnis_empfaenger', None)
        if ergebnis_empfaenger is not None:
            if ergebnis_empfaenger.count() == 1:
                return False

    return show_summary_form


def show_tutor_form(wizard):
    show_summary_form = perform_evalution(wizard)
    if show_summary_form:
        cleaned_data = wizard.get_cleaned_data_for_step('basisdaten') or {}
        v_typ = cleaned_data.get('typ', '')
        return v_typ == "vu"
    return show_summary_form


class VeranstalterWizard(SessionWizardView):
    form_list = [
        ('evaluation', VeranstaltungEvaluationForm),
        ('basisdaten', VeranstaltungBasisdatenForm),
        ('primaerdozent', VeranstaltungPrimaerDozentForm),
        ('verantwortlicher_address', VeranstaltungDozentDatenForm),
        ('freie_fragen', VeranstaltungFreieFragen),
        ('tutoren', VeranstaltungTutorenForm),
        ('zusammenfassung', forms.Form)
    ]

    condition_dict = {
        'basisdaten': perform_evalution,
        'primaerdozent': show_primaerdozent_form,
        'verantwortlicher_address': perform_evalution,
        'freie_fragen': perform_evalution,
        'tutoren': show_tutor_form
    }

    def get_instance(self):
        return Veranstaltung.objects.get(id=self.request.session['vid'])

    def get(self, request, *args, **kwargs):
        if self.request.user.username != settings.USERNAME_VERANSTALTER:
            return render(self.request, 'veranstalter/not_authenticated.html')
        return super(VeranstalterWizard, self).get(request, *args, **kwargs)

    def get_context_data(self, form, **kwargs):
        context = super(VeranstalterWizard, self).get_context_data(form=form, **kwargs)
        context.update({'veranstaltung': self.get_instance()})
        if self.steps.current == "zusammenfassung":
            all_form_data = []
            for step_form in self.form_list:
                form_obj = self.get_form(
                    step=step_form,
                    data=self.storage.get_step_data(step_form),
                    files=self.storage.get_step_files(step_form),
                )
                if form_obj.is_valid():
                    for field_key, field_obj in form_obj.fields.items():
                        cleaned_d = form_obj.cleaned_data[field_key]
                        field_value = ""
                        if isinstance(field_obj, forms.fields.BooleanField):
                            field_value = "Ja" if cleaned_d else "Nein"
                        elif isinstance(field_obj, forms.fields.TypedChoiceField):
                            for key, choice in field_obj.choices:
                                if key == cleaned_d:
                                    field_value = choice
                                    break
                        else:
                            field_value = form_obj.cleaned_data[field_key]

                        field_label = field_obj.label
                        if field_label is None:
                            field_label = field_key
                        all_form_data.append({
                            'label': field_label,
                            'value': field_value
                        })
            context.update({'all_form_data':  all_form_data})
        return context

    def get_form_instance(self, step):
        if step == "verantwortlicher_address":
            basisdaten = self.get_cleaned_data_for_step('basisdaten')
            if basisdaten:
                return basisdaten["verantwortlich"]
        return self.get_instance()

    def get_form_kwargs(self, step=None):
        kwargs = super(VeranstalterWizard, self).get_form_kwargs(step)
        if step == 'primaerdozent':
            basisdaten = self.get_cleaned_data_for_step('basisdaten')
            if basisdaten is not None:
                kwargs.update({'basisdaten': basisdaten})
        elif step == 'tutoren':
            veranstaltung = self.get_form_instance(step)
            if veranstaltung is not None:
                kwargs.update({'preset_csv': veranstaltung.kleingruppen})
        return kwargs

    def get_template_names(self):
        return [VERANSTALTER_VIEW_TEMPLATES[self.steps.current]]

    def done(self, form_list, **kwargs):
        if not any(isinstance(x, VeranstaltungPrimaerDozentForm) for x in form_list):
            # preselect primaer dozent
            cleaned_data = self.get_cleaned_data_for_step('basisdaten') or {}
            ergebnis_empfaenger = cleaned_data.get('ergebnis_empfaenger', None)
            if ergebnis_empfaenger is not None:
                form_primar = VeranstaltungPrimaerDozentForm(is_dynamic_form=True,
                                                             data={'primaerdozent': ergebnis_empfaenger[0].id},
                                                             instance=self.get_instance())
                form_primar.is_valid()
                form_list.append(form_primar)

        instance = self.get_instance()

        save_to_db(self.request, instance, form_list)

        for e in ergebnis_empfaenger:
            send_mail(
                'Evaluation der Lehrveranstaltungen - Zusammenfassung der Daten',
                'Here is the message.',
                settings.DEFAULT_FROM_EMAIL,
                [e.email],
                fail_silently=False,
            )

        return render_to_response('formtools/wizard/bestellung_done.html', )


def save_to_db(request, instance, form_list):
    """
    Speichert alle eingegebenen Daten des Wizards auf das Modell
    und setzt den Status einer Veranstaltung auf den nächsten validen Zustand
    """
    for form in form_list:
        for key, val in form.cleaned_data.iteritems():
            if isinstance(form, VeranstaltungTutorenForm):
                if key == "csv_tutoren":
                    instance.csv_to_tutor(val)
                    setattr(instance, "kleingruppen", val)
            elif isinstance(form.instance, Veranstaltung):
                setattr(instance, key, val)
            else:
                setattr(form.instance, key, val)

        if not isinstance(form, VeranstaltungTutorenForm) \
                and hasattr(form, 'instance') and not isinstance(form.instance, Veranstaltung):
            form.instance.save()

    instance.set_next_state()
    instance.save()
    instance.log(request.user, is_frontend=True)
<commit_msg>fixed email function<commit_after># coding=utf-8

from django import forms
from django.conf import settings
from django.views.decorators.http import require_safe
from django.contrib import auth
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.shortcuts import render_to_response
from formtools.wizard.views import SessionWizardView
from feedback.models import Veranstaltung
from feedback.forms import VeranstaltungEvaluationForm, VeranstaltungBasisdatenForm, VeranstaltungPrimaerDozentForm, \
    VeranstaltungDozentDatenForm, VeranstaltungFreieFragen, VeranstaltungTutorenForm
from django.core.mail import send_mail


@require_safe
def login(request):
    if 'vid' in request.GET and 'token' in request.GET:
        vid = int(request.GET['vid'])
        token = unicode(request.GET['token'])

        user = auth.authenticate(vid=vid, token=token)
        if user:
            auth.login(request, user)
            v = Veranstaltung.objects.get(id=vid)
            request.session['vid'] = v.id
            request.session['veranstaltung'] = unicode(v)

            if v.status == Veranstaltung.STATUS_BESTELLUNG_LIEGT_VOR or \
                    v.status == Veranstaltung.STATUS_BESTELLUNG_GEOEFFNET:
                return HttpResponseRedirect(reverse('veranstalter-index'))

    return render(request, 'veranstalter/login_failed.html')


VERANSTALTER_VIEW_TEMPLATES = {
    "evaluation": "formtools/wizard/evaluation.html",
    "basisdaten": "formtools/wizard/basisdaten.html",
    "primaerdozent": "formtools/wizard/primaerdozent.html",
    "verantwortlicher_address": "formtools/wizard/address.html",
    "freie_fragen": "formtools/wizard/freiefragen.html",
    "tutoren": "formtools/wizard/tutoren.html",
    "zusammenfassung": "formtools/wizard/zusammenfassung.html"
}


def perform_evalution(wizard):
    """
    Wenn wir keine Vollerhebung haben, und der Veranstalter nicht evauliert, dann
    springt der Wizard direkt zur Zusammenfassung.
    """
    cleaned_data = wizard.get_cleaned_data_for_step('evaluation') or {}
    v = Veranstaltung.objects.get(id=wizard.request.session['vid'])

    if v.semester.vollerhebung:
        return True

    return cleaned_data.get('evaluieren', True)


def show_primaerdozent_form(wizard):
    show_summary_form = perform_evalution(wizard)
    if show_summary_form:
        cleaned_data = wizard.get_cleaned_data_for_step('basisdaten') or {}
        ergebnis_empfaenger = cleaned_data.get('ergebnis_empfaenger', None)
        if ergebnis_empfaenger is not None:
            if ergebnis_empfaenger.count() == 1:
                return False

    return show_summary_form


def show_tutor_form(wizard):
    show_summary_form = perform_evalution(wizard)
    if show_summary_form:
        cleaned_data = wizard.get_cleaned_data_for_step('basisdaten') or {}
        v_typ = cleaned_data.get('typ', '')
        return v_typ == "vu"
    return show_summary_form


class VeranstalterWizard(SessionWizardView):
    form_list = [
        ('evaluation', VeranstaltungEvaluationForm),
        ('basisdaten', VeranstaltungBasisdatenForm),
        ('primaerdozent', VeranstaltungPrimaerDozentForm),
        ('verantwortlicher_address', VeranstaltungDozentDatenForm),
        ('freie_fragen', VeranstaltungFreieFragen),
        ('tutoren', VeranstaltungTutorenForm),
        ('zusammenfassung', forms.Form)
    ]

    condition_dict = {
        'basisdaten': perform_evalution,
        'primaerdozent': show_primaerdozent_form,
        'verantwortlicher_address': perform_evalution,
        'freie_fragen': perform_evalution,
        'tutoren': show_tutor_form
    }

    def get_instance(self):
        return Veranstaltung.objects.get(id=self.request.session['vid'])

    def get(self, request, *args, **kwargs):
        if self.request.user.username != settings.USERNAME_VERANSTALTER:
            return render(self.request, 'veranstalter/not_authenticated.html')
        return super(VeranstalterWizard, self).get(request, *args, **kwargs)

    def get_context_data(self, form, **kwargs):
        context = super(VeranstalterWizard, self).get_context_data(form=form, **kwargs)
        context.update({'veranstaltung': self.get_instance()})
        if self.steps.current == "zusammenfassung":
            all_form_data = []
            for step_form in self.form_list:
                form_obj = self.get_form(
                    step=step_form,
                    data=self.storage.get_step_data(step_form),
                    files=self.storage.get_step_files(step_form),
                )
                if form_obj.is_valid():
                    for field_key, field_obj in form_obj.fields.items():
                        cleaned_d = form_obj.cleaned_data[field_key]
                        field_value = ""
                        if isinstance(field_obj, forms.fields.BooleanField):
                            field_value = "Ja" if cleaned_d else "Nein"
                        elif isinstance(field_obj, forms.fields.TypedChoiceField):
                            for key, choice in field_obj.choices:
                                if key == cleaned_d:
                                    field_value = choice
                                    break
                        else:
                            field_value = form_obj.cleaned_data[field_key]

                        field_label = field_obj.label
                        if field_label is None:
                            field_label = field_key
                        all_form_data.append({
                            'label': field_label,
                            'value': field_value
                        })
            context.update({'all_form_data':  all_form_data})
        return context

    def get_form_instance(self, step):
        if step == "verantwortlicher_address":
            basisdaten = self.get_cleaned_data_for_step('basisdaten')
            if basisdaten:
                return basisdaten["verantwortlich"]
        return self.get_instance()

    def get_form_kwargs(self, step=None):
        kwargs = super(VeranstalterWizard, self).get_form_kwargs(step)
        if step == 'primaerdozent':
            basisdaten = self.get_cleaned_data_for_step('basisdaten')
            if basisdaten is not None:
                kwargs.update({'basisdaten': basisdaten})
        elif step == 'tutoren':
            veranstaltung = self.get_form_instance(step)
            if veranstaltung is not None:
                kwargs.update({'preset_csv': veranstaltung.kleingruppen})
        return kwargs

    def get_template_names(self):
        return [VERANSTALTER_VIEW_TEMPLATES[self.steps.current]]

    def done(self, form_list, **kwargs):
        cleaned_data = self.get_cleaned_data_for_step('basisdaten') or {}
        ergebnis_empfaenger = cleaned_data.get('ergebnis_empfaenger', None)
        if not any(isinstance(x, VeranstaltungPrimaerDozentForm) for x in form_list):
            # preselect primaer dozent
            if ergebnis_empfaenger is not None:
                form_primar = VeranstaltungPrimaerDozentForm(is_dynamic_form=True,
                                                             data={'primaerdozent': ergebnis_empfaenger[0].id},
                                                             instance=self.get_instance())
                form_primar.is_valid()
                form_list.append(form_primar)

        instance = self.get_instance()

        save_to_db(self.request, instance, form_list)

        if ergebnis_empfaenger is not None:
            for e in ergebnis_empfaenger:
                send_mail(
                    'Evaluation der Lehrveranstaltungen - Zusammenfassung der Daten',
                    'Here is the message.',
                    settings.DEFAULT_FROM_EMAIL,
                    [e.email],
                    fail_silently=False,
                )

        return render_to_response('formtools/wizard/bestellung_done.html', )


def save_to_db(request, instance, form_list):
    """
    Speichert alle eingegebenen Daten des Wizards auf das Modell
    und setzt den Status einer Veranstaltung auf den nächsten validen Zustand
    """
    for form in form_list:
        for key, val in form.cleaned_data.iteritems():
            if isinstance(form, VeranstaltungTutorenForm):
                if key == "csv_tutoren":
                    instance.csv_to_tutor(val)
                    setattr(instance, "kleingruppen", val)
            elif isinstance(form.instance, Veranstaltung):
                setattr(instance, key, val)
            else:
                setattr(form.instance, key, val)

        if not isinstance(form, VeranstaltungTutorenForm) \
                and hasattr(form, 'instance') and not isinstance(form.instance, Veranstaltung):
            form.instance.save()

    instance.set_next_state()
    instance.save()
    instance.log(request.user, is_frontend=True)

{'fraction_non_alphanumeric': 0.0870951501929854, 'fraction_numerical': 0.0003356267830172848, 'mean_word_length': 2.356740518212542, 'pattern_counts': {'":': 20, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6594097', 'n_tokens_mistral': 5371, 'n_tokens_neox': 5263, 'n_words': 969}