Skip to content
Snippets Groups Projects
mails.py 4.49 KiB
Newer Older
# coding=utf-8
import logging
logger = logging.getLogger(__name__)
Valentin Groues's avatar
Valentin Groues committed
import StringIO
from wsgiref.util import FileWrapper

from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.views.generic import CreateView
from django.views.generic import DeleteView
from django.views.generic import ListView
from django.views.generic import UpdateView

from web.docx_helper import merge_files
Piotr Gawron's avatar
Piotr Gawron committed
from . import WrappedView
from ..models import StudySubject, Visit, Appointment, MailTemplate, Voucher
Valentin Groues's avatar
Valentin Groues committed
from ..models.constants import MAIL_TEMPLATE_CONTEXT_SUBJECT, MAIL_TEMPLATE_CONTEXT_VISIT, \
    MAIL_TEMPLATE_CONTEXT_APPOINTMENT, MAIL_TEMPLATE_CONTEXT_VOUCHER
Valentin Groues's avatar
Valentin Groues committed

MIMETYPE_DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

CONTEXT_TYPES_MAPPING = {
    MAIL_TEMPLATE_CONTEXT_SUBJECT: StudySubject,
Valentin Groues's avatar
Valentin Groues committed
    MAIL_TEMPLATE_CONTEXT_VISIT: Visit,
    MAIL_TEMPLATE_CONTEXT_VOUCHER: Voucher,
Valentin Groues's avatar
Valentin Groues committed
    MAIL_TEMPLATE_CONTEXT_APPOINTMENT: Appointment
}
Valentin Groues's avatar
Valentin Groues committed
class MailTemplatesListView(ListView, WrappedView):
    model = MailTemplate
    context_object_name = "mail_templates"
    template_name = 'mail_templates/list.html'

    def get_context_data(self, **kwargs):
        context = super(MailTemplatesListView, self).get_context_data()
        context['explanations'] = {"generic": MailTemplate.MAILS_TEMPLATE_GENERIC_TAGS,
                                   "subject": MailTemplate.MAILS_TEMPLATE_SUBJECT_TAGS,
                                   "visit": MailTemplate.MAILS_TEMPLATE_VISIT_TAGS,
                                   "voucher": MailTemplate.MAILS_TEMPLATE_VOUCHER_TAGS,
Valentin Groues's avatar
Valentin Groues committed
                                   "appointment": MailTemplate.MAILS_TEMPLATE_APPOINTMENT_TAGS,
                                   }
        return context


class MailTemplatesCreateView(CreateView, WrappedView):
    model = MailTemplate
    template_name = "mail_templates/add.html"
    fields = '__all__'
    success_url = reverse_lazy('web.views.mail_templates')
    success_message = "Template created"


class MailTemplatesDeleteView(DeleteView, WrappedView):
    model = MailTemplate
    success_url = reverse_lazy('web.views.mail_templates')
    template_name = 'mail_templates/confirm_delete.html'

    def delete(self, request, *args, **kwargs):
        messages.success(request, "Template deleted")
        return super(MailTemplatesDeleteView, self).delete(request, *args, **kwargs)


class MailTemplatesEditView(UpdateView, WrappedView):
    model = MailTemplate
    success_url = reverse_lazy('web.views.mail_templates')
    fields = '__all__'
    success_message = "Template edited"
    template_name = "mail_templates/edit.html"
    context_object_name = "mail_template"


def generate(request, mail_template_id, instance_id):
    mail_template = get_object_or_404(MailTemplate, id=mail_template_id)
    instance = get_object_or_404(CONTEXT_TYPES_MAPPING[mail_template.context], id=instance_id)
    stream = StringIO.StringIO()
    stream = mail_template.apply(instance, request.user, stream)
    file_size = stream.tell()
    stream.seek(0)
    response = HttpResponse(FileWrapper(stream), content_type=MIMETYPE_DOCX)
    response['Content-Length'] = file_size
    response['Content-Disposition'] = 'attachment; filename={}.docx'.format(mail_template.name)
    return response


def generate_for_vouchers(request):
    ids = request.GET.get('voucher_id', '').split(',')
    vouchers = []
    for voucher_id in ids:
        if voucher_id.isdigit():
            voucher = Voucher.objects.get(pk=int(voucher_id))
            vouchers.append(voucher)
            try:
                languages.extend(voucher.study_subject.subject.languages.all())
            except: #if no languages or no subject or no study subject 
                continue
    templates = MailTemplate.get_voucher_mail_templates(list(set(languages)))[0]

    output_stream = StringIO.StringIO()

    inputs = []
    for template in templates:
        for voucher in vouchers:
            input_stream = StringIO.StringIO()
            input_stream = template.apply(voucher, request.user, input_stream)
            input_stream.seek(0)
            inputs.append(input_stream)

    merge_files(inputs, output_stream)
    file_size = output_stream.tell()
    output_stream.seek(0)
    response = HttpResponse(FileWrapper(output_stream), content_type=MIMETYPE_DOCX)
    response['Content-Length'] = file_size
    response['Content-Disposition'] = 'attachment; filename=vouchers.docx'
    return response