# coding=utf-8 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 . import WrappedView from ..models import StudySubject, Visit, Appointment, MailTemplate from ..models.constants import MAIL_TEMPLATE_CONTEXT_SUBJECT, MAIL_TEMPLATE_CONTEXT_VISIT, \ MAIL_TEMPLATE_CONTEXT_APPOINTMENT MIMETYPE_DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' CONTEXT_TYPES_MAPPING = { MAIL_TEMPLATE_CONTEXT_SUBJECT: StudySubject, MAIL_TEMPLATE_CONTEXT_VISIT: Visit, MAIL_TEMPLATE_CONTEXT_APPOINTMENT: Appointment } 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, "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