Esempio n. 1
0
    def __init__(self, *args, **kwargs):
        """
        Overloading super().__init__() to make accounts available as assignees
        """
        super(CreateUpdateDealForm, self).__init__(*args, **kwargs)

        # FIXME: WORKAROUND FOR TENANT FILTER.
        # An error will occur when using LilyUser.objects.all(), most likely because
        # the foreign key to contact (and maybe account) is filtered and executed before
        # the filter for the LilyUser. This way it's possible contacts (and maybe accounts)
        # won't be found for a user. But since it's a required field, an exception is raised.
        self.fields['assigned_to'].queryset = LilyUser.objects.filter(tenant=get_current_user().tenant)
        self.fields['assigned_to'].initial = get_current_user()
Esempio n. 2
0
    def __init__(self, *args, **kwargs):
        """
        Overloading super().__init__() to make accounts available as assignees
        """
        super(CreateUpdateDealForm, self).__init__(*args, **kwargs)

        # FIXME: WORKAROUND FOR TENANT FILTER.
        # An error will occur when using LilyUser.objects.all(), most likely because
        # the foreign key to contact (and maybe account) is filtered and executed before
        # the filter for the LilyUser. This way it's possible contacts (and maybe accounts)
        # won't be found for a user. But since it's a required field, an exception is raised.
        self.fields['assigned_to'].queryset = LilyUser.objects.filter(tenant=get_current_user().tenant)
        self.fields['assigned_to'].initial = get_current_user()
Esempio n. 3
0
    def delete(self, request, *args, **kwargs):
        """
        Overloading super().delete to check if the user who tries to delete this entry is also the
        author.
        """
        self.object = self.get_object()

        # Check if this blog entry account is written by request.user
        if self.object.author != get_current_user():
            raise Http404()

        # Show delete message
        messages.success(self.request, _('Post deleted.'))

        self.object.delete()

        if is_ajax(request):
            do_redirect = True
            url = request.META.get('HTTP_REFERER', reverse('dashboard'))

            # Return response
            return HttpResponse(anyjson.serialize({
                'error': False,
                'redirect_url': url
            }), content_type='application/json')

        return redirect(request.META.get('HTTP_REFERER', reverse('dashboard')))
Esempio n. 4
0
    def __init__(self, *args, **kwargs):
        self.draft_id = kwargs.pop('draft_id', None)
        self.message_type = kwargs.pop('message_type', 'reply')
        super(ComposeEmailForm, self).__init__(*args, **kwargs)

        if self.message_type is not 'reply':
            self.fields['attachments'].initial = EmailAttachment.objects.filter(message_id=self.draft_id)

        user = get_current_user()
        email_accounts = user.get_messages_accounts(EmailAccount)

        # Only provide choices you have access to
        self.fields['send_from'].choices = [(email_account.id, email_account) for email_account in email_accounts]
        self.fields['send_from'].empty_label = None

        # Set user's primary_email as default choice if there is no initial value
        initial_email_account = self.initial.get('send_from', None)
        if not initial_email_account:
            for email_account in email_accounts:
                if user.primary_email and email_account.email.email_address == user.primary_email.email_address:
                    initial_email_account = email_account
        elif isinstance(initial_email_account, basestring):
            for email_account in email_accounts:
                if email_account.email.email_address == initial_email_account:
                    initial_email_account = email_account

        self.initial['send_from'] = initial_email_account
Esempio n. 5
0
    def get_form_kwargs(self):
        kwargs = super(EmailMessageComposeView, self).get_form_kwargs()
        kwargs['message_type'] = 'new'

        email_address = self.kwargs.get('email_address', None)
        template = self.kwargs.get('template', None)

        if template:
            try:
                EmailTemplate.objects.get(pk=template)
            except EmailTemplate.DoesNotExist:
                try:
                    DefaultEmailTemplate.objects.get(user=get_current_user())
                except DefaultEmailTemplate.DoesNotExist:
                    message = _(
                        'Sorry, I couldn\'t load the given template. Please try a different one.'
                    )
                else:
                    message = _(
                        'Sorry, I couldn\'t load the given template. '
                        'I\'ll load your default email template instead.')

                messages.warning(self.request, message)
                template = None

        kwargs.update({
            'initial': {
                'send_to_normal': email_address,
                'template': template,
            },
        })

        return kwargs
Esempio n. 6
0
    def __init__(self, *args, **kwargs):
        """
        Overload super().__init__ to change the appearance of the form and add parameter fields if necessary.
        """
        self.draft_id = kwargs.pop('draft_id', None)
        self.message_type = kwargs.pop('message_type', 'reply')
        super(CreateUpdateEmailTemplateForm, self).__init__(*args, **kwargs)

        email_parameter_choices = get_email_parameter_choices()
        self.fields['variables'].choices += [[x, x] for x in email_parameter_choices.keys()]
        self.fields['variables'].choices.append(['Custom variables', 'Custom variables'])

        for value in email_parameter_choices:
            for val in email_parameter_choices[value]:
                self.fields['values'].choices += [[val, email_parameter_choices[value][val]], ]

        # Add custom variables to choices
        queryset = TemplateVariable.objects.all().filter(Q(is_public=True) | Q(owner=get_current_user()))

        for template_variable in queryset:
            custom_variable_name = 'custom.' + template_variable.name.lower()

            if template_variable.is_public:
                custom_variable_name += '.public'

            self.fields['values'].choices += [[custom_variable_name, template_variable.name], ]

        if self.instance and self.instance.pk:
            self.fields['id'].widget.attrs['readonly'] = True

        self.fields['attachments'].initial = EmailTemplateAttachment.objects.filter(template_id=self.instance.id)
Esempio n. 7
0
    def get_form_kwargs(self):
        kwargs = super(EmailMessageComposeView, self).get_form_kwargs()
        kwargs['message_type'] = 'new'

        email_address = self.kwargs.get('email_address', None)
        template = self.kwargs.get('template', None)

        if template:
            try:
                EmailTemplate.objects.get(pk=template)
            except EmailTemplate.DoesNotExist:
                try:
                    DefaultEmailTemplate.objects.get(user=get_current_user())
                except DefaultEmailTemplate.DoesNotExist:
                    message = _('Sorry, I couldn\'t load the given template. Please try a different one.')
                else:
                    message = _('Sorry, I couldn\'t load the given template. '
                                'I\'ll load your default email template instead.')

                messages.warning(self.request, message)
                template = None

        kwargs.update({
            'initial': {
                'send_to_normal': email_address,
                'template': template,
            },
        })

        return kwargs
Esempio n. 8
0
    def __init__(self, *args, **kwargs):
        """
        Overload super().__init__ to change the appearance of the form and add parameter fields if necessary.
        """
        self.draft_id = kwargs.pop('draft_id', None)
        self.message_type = kwargs.pop('message_type', 'reply')
        super(CreateUpdateEmailTemplateForm, self).__init__(*args, **kwargs)

        email_parameter_choices = get_email_parameter_choices()
        self.fields['variables'].choices += [[x, x] for x in email_parameter_choices.keys()]
        self.fields['variables'].choices.append(['Custom variables', 'Custom variables'])

        for value in email_parameter_choices:
            for val in email_parameter_choices[value]:
                self.fields['values'].choices += [[val, email_parameter_choices[value][val]], ]

        # Add custom variables to choices
        queryset = TemplateVariable.objects.all().filter(Q(is_public=True) | Q(owner=get_current_user()))

        for template_variable in queryset:
            custom_variable_name = 'custom.' + template_variable.name.lower()

            if template_variable.is_public:
                custom_variable_name += '.public'

            self.fields['values'].choices += [[custom_variable_name, template_variable.name], ]

        if self.instance and self.instance.pk:
            self.fields['id'].widget.attrs['readonly'] = True

        self.fields['attachments'].initial = EmailTemplateAttachment.objects.filter(template_id=self.instance.id)
Esempio n. 9
0
    def __init__(self, *args, **kwargs):
        """
        Set queryset and initial for *assign_to*
        """
        super(CreateUpdateCaseForm, self).__init__(*args, **kwargs)

        # FIXME: WORKAROUND FOR TENANT FILTER.
        # An error will occur when using LilyUser.objects.all(), most likely because
        # the foreign key to contact (and maybe account) is filtered and executed before
        # the filter for the LilyUser. This way it's possible contacts (and maybe accounts)
        # won't be found for a user. But since it's a required field, an exception is raised.
        user = get_current_user()
        self.fields['assigned_to'].queryset = LilyUser.objects.filter(tenant=user.tenant)
        self.fields['expires'].initial = datetime.today()

        # Pre-select users team if possible
        groups = user.lily_groups.all()
        if len(groups) == 1:
            self.fields['assigned_to_groups'].initial = groups

        # Setup parcel initial values
        self.fields['parcel_provider'].initial = Parcel.DPD
        self.fields['status'].initial = CaseStatus.objects.first()

        self.fields['type'].queryset = CaseType.objects.filter(is_archived=False)

        if self.instance.parcel is not None:
            self.fields['parcel_provider'].initial = self.instance.parcel.provider
            self.fields['parcel_identifier'].initial = self.instance.parcel.identifier
Esempio n. 10
0
    def __init__(self, *args, **kwargs):
        """
        Set queryset and initial for *assign_to*
        """
        super(CreateUpdateCaseForm, self).__init__(*args, **kwargs)

        # FIXME: WORKAROUND FOR TENANT FILTER.
        # An error will occur when using LilyUser.objects.all(), most likely because
        # the foreign key to contact (and maybe account) is filtered and executed before
        # the filter for the LilyUser. This way it's possible contacts (and maybe accounts)
        # won't be found for a user. But since it's a required field, an exception is raised.
        user = get_current_user()
        self.fields['assigned_to'].queryset = LilyUser.objects.filter(
            tenant=user.tenant)
        self.fields['expires'].initial = datetime.today()

        # Pre-select users team if possible
        groups = user.lily_groups.all()
        if len(groups) == 1:
            self.fields['assigned_to_groups'].initial = groups

        # Setup parcel initial values
        self.fields['parcel_provider'].initial = Parcel.DPD
        self.fields['status'].initial = CaseStatus.objects.first()

        self.fields['type'].queryset = CaseType.objects.filter(
            is_archived=False)

        if self.instance.parcel is not None:
            self.fields[
                'parcel_provider'].initial = self.instance.parcel.provider
            self.fields[
                'parcel_identifier'].initial = self.instance.parcel.identifier
Esempio n. 11
0
    def clean_old_password(self):
        old_password = self.cleaned_data['old_password']
        logged_in_user = get_current_user()

        if not logged_in_user.check_password(old_password):
            self._errors["old_password"] = self.error_class([_('Password is incorrect.')])

        return old_password
Esempio n. 12
0
    def save(self, *args, **kwargs):
        user = get_current_user()

        # Only set the tenant if it's a new tenant and a user is logged in
        if not self.id and user and user.is_authenticated():
            self.tenant = user.tenant

        return super(NullableTenantMixin, self).save(*args, **kwargs)
Esempio n. 13
0
 def __init__(self, *args, **kwargs):
     super(EmailTemplateSetDefaultForm, self).__init__(*args, **kwargs)
     user = get_current_user()
     self.fields['default_for'].queryset = EmailAccount.objects.filter(
         Q(owner=user) |
         Q(public=True) |
         Q(shared_with_users__id=user.pk)
     ).filter(tenant=user.tenant).distinct('id')
Esempio n. 14
0
 def __init__(self, *args, **kwargs):
     super(EmailTemplateSetDefaultForm, self).__init__(*args, **kwargs)
     user = get_current_user()
     self.fields['default_for'].queryset = EmailAccount.objects.filter(
         Q(owner=user) |
         Q(public=True) |
         Q(shared_with_users__id=user.pk)
     ).filter(tenant=user.tenant).distinct('id')
Esempio n. 15
0
    def save(self, commit=True):
        new_password = self.cleaned_data.get('new_password1')
        if new_password:
            logged_in_user = get_current_user()
            logged_in_user.set_password(new_password)
            logged_in_user.save()

        return super(UserAccountForm, self).save(commit)
Esempio n. 16
0
    def __init__(self, *args, **kwargs):
        """
        Overload super().__init__ to change the appearance of the form.
        """
        self.original_user = kwargs.pop('original_user', None)
        super(EmailShareForm, self).__init__(*args, **kwargs)

        # Exclude original user from queryset when provided
        if self.original_user is not None:
            self.fields['user_group'].queryset = CustomUser.objects.filter(tenant=get_current_user().tenant).exclude(pk=self.original_user.pk)
        else:
            self.fields['user_group'].queryset = CustomUser.objects.filter(tenant=get_current_user().tenant)

        # Overwrite help_text
        self.fields['user_group'].help_text = ''

        # Only a required field when selecting 'Specific users'
        self.fields['user_group'].required = False
Esempio n. 17
0
def get_folder_unread_count(folder, email_accounts=None):
    """
    Return the number of unread email messages in folder for given email accounts.
    """
    from lily.messaging.email.models import EmailAccount, EmailMessage  # prevent circular dependency
    if email_accounts is None:
        email_accounts = get_current_user().get_messages_accounts(EmailAccount)

    return EmailMessage.objects.filter(Q(folder_identifier=folder) | Q(folder_name=folder), account__in=email_accounts, is_seen=False).count()
Esempio n. 18
0
 def get_query_set(self):
     """
     Manipulate the returned queryset by adding a filter for tenant using the tenant linked
     to the current logged in user (received via custom middleware).
     """
     user = get_current_user()
     if user and user.is_authenticated():
         return super(TenantManager, self).get_query_set().filter(tenant=user.tenant)
     else:
         return super(TenantManager, self).get_query_set()
Esempio n. 19
0
def post_save_invite_callback(sender, instance, created, **kwargs):
    if settings.TESTING:
        return

    if created:
        user = get_current_user()
        analytics.track(
            user.id, 'invite-created', {
                'email': instance.email,
                'tenant_id': instance.tenant.id,
                'date': instance.date,
            })
Esempio n. 20
0
    def save(self, commit=True):
        instance = super(CreateUpdateTemplateVariableForm, self).save(False)

        # Convert \n to <br>
        instance.text = linebreaksbr(instance.text.strip())

        instance.owner = get_current_user()

        if commit:
            instance.save()

        return instance
Esempio n. 21
0
 def _get_logged_in_user(self):
     tenant = TenantFactory()
     current_user = get_current_user()
     # Ugly!
     if current_user:
         current_user.tenant = tenant
     user = LilyUserFactory(tenant=tenant)
     user.set_password('test')
     user.save()
     self.client.login(username=user.primary_email.email_address,
                       password='******')
     return user
Esempio n. 22
0
 def get_queryset(self):
     """
     Manipulate the returned queryset by adding a filter for tenant using the tenant linked
     to the current logged in user (received via custom middleware).
     """
     user = get_current_user()
     if user and user.is_authenticated():
         qs = super(ElasticTenantManager,
                    self).get_queryset().filter(tenant_id=user.tenant_id)
         return qs.elasticsearch_query(Term(tenant_id=user.tenant_id))
     else:
         return super(ElasticTenantManager, self).get_queryset()
Esempio n. 23
0
    def save(self, commit=True):
        instance = super(CreateUpdateTemplateVariableForm, self).save(False)

        # Convert \n to <br>
        instance.text = linebreaksbr(instance.text.strip())

        instance.owner = get_current_user()

        if commit:
            instance.save()

        return instance
Esempio n. 24
0
    def get_or_create_draft(self):
        """
        Both _create_object and get_url require an email draft, while some tests make that only one of these
        functions are called. To simplify, we use this method to return a draft when there isn't one.
        """
        if hasattr(self, 'email_draft'):
            return self.email_draft

        user = get_current_user()
        email_account = EmailAccountFactory.create(owner=user, tenant=user.tenant)
        self.email_draft = EmailDraftFactory(tenant=user.tenant, send_from=email_account)

        return self.email_draft
Esempio n. 25
0
    def __init__(self, *args, **kwargs):
        """
        Set queryset and initial for *assign_to*
        """
        super(CreateUpdateCaseForm, self).__init__(*args, **kwargs)

        # FIXME: WORKAROUND FOR TENANT FILTER.
        # An error will occur when using CustomUser.objects.all(), most likely because
        # the foreign key to contact (and maybe account) is filtered and executed before
        # the filter for the CustomUser. This way it's possible contacts (and maybe accounts)
        # won't be found for a user. But since it's a required field, an exception is raised.
        #
        self.fields['assigned_to'].queryset = CustomUser.objects.filter(tenant=get_current_user().tenant)
        self.fields['assigned_to'].initial = get_current_user()
        self.fields['expires'].initial = datetime.today()

        # Setup parcel initial values
        self.fields['parcel_provider'].initial = Parcel.DPD

        if self.instance.parcel is not None:
            self.fields['parcel_provider'].initial = self.instance.parcel.provider
            self.fields['parcel_identifier'].initial = self.instance.parcel.identifier
Esempio n. 26
0
    def __init__(self, *args, **kwargs):
        self.message_type = kwargs.pop('message_type', 'reply')
        super(ComposeEmailForm, self).__init__(*args, **kwargs)

        # Only show the checkbox for existing attachments if we have a pk and if we forward.
        if 'initial' in kwargs and 'draft_pk' in kwargs[
                'initial'] and self.message_type == 'forward':
            existing_attachment_list = EmailAttachment.objects.filter(
                message_id=kwargs['initial']['draft_pk'], inline=False)
            choices = [(attachment.id, attachment.name)
                       for attachment in existing_attachment_list]
            self.fields['existing_attachments'] = forms.MultipleChoiceField(
                choices=choices,
                widget=forms.CheckboxSelectMultiple,
                initial=[a.id for a in existing_attachment_list],
                required=False,
            )

        self.fields['template'].queryset = EmailTemplate.objects.order_by(
            'name')

        user = get_current_user()

        email_account_list = get_shared_email_accounts(user)

        self.email_accounts = email_account_list

        # Only provide choices you have access to
        self.fields['send_from'].choices = [
            (email_account.id, email_account)
            for email_account in self.email_accounts
        ]
        self.fields['send_from'].empty_label = None

        # Set user's primary_email as default choice if there is no initial value
        initial_email_account = self.initial.get('send_from', None)
        if not initial_email_account:
            if user.primary_email_account:
                initial_email_account = user.primary_email_account.id
            else:
                for email_account in self.email_accounts:
                    if email_account.email_address == user.email:
                        initial_email_account = email_account
                        break
        elif isinstance(initial_email_account, basestring):
            for email_account in self.email_accounts:
                if email_account.email == initial_email_account:
                    initial_email_account = email_account
                    break

        self.initial['send_from'] = initial_email_account
Esempio n. 27
0
def add_tenant(model, tenant=None):
    if isinstance(model, models.Model):
        user = get_current_user()
        
        if tenant:
            pass
        elif user and user.is_authenticated():
            tenant = user.tenant
        else:
            tenant = Tenant.objects.create()
        
        model.tenant = tenant
    
    return model, tenant
Esempio n. 28
0
    def clean(self):
        cleaned_data = super(CreateUpdateTemplateVariableForm, self).clean()

        queryset = TemplateVariable.objects.filter(
            name__iexact=cleaned_data.get('name'), owner=get_current_user())

        # Check if variable already exists, but only when creating a new one
        if self.instance:
            queryset = queryset.exclude(id=self.instance.id)
        if queryset.exists():
            self._errors['name'] = [
                'Template variable with that name already exists for this user'
            ]

        return cleaned_data
Esempio n. 29
0
    def clean_send_from(self):
        """
        Verify send_from is a valid account the user has access to.
        """
        cleaned_data = self.cleaned_data
        send_from = cleaned_data.get('send_from')

        email_accounts = get_current_user().get_messages_accounts(EmailAccount)
        if send_from.pk not in [account.pk for account in email_accounts]:
            raise ValidationError(
                _('Invalid email account selected to use as sender.'),
                code='invalid',
            )
        else:
            return send_from
Esempio n. 30
0
    def get_or_create_draft(self):
        """
        Both _create_object and get_url require an email draft, while some tests make that only one of these
        functions are called. To simplify, we use this method to return a draft when there isn't one.
        """
        if hasattr(self, 'email_draft'):
            return self.email_draft

        user = get_current_user()
        email_account = EmailAccountFactory.create(owner=user,
                                                   tenant=user.tenant)
        self.email_draft = EmailDraftFactory(tenant=user.tenant,
                                             send_from=email_account)

        return self.email_draft
Esempio n. 31
0
    def __init__(self, *args, **kwargs):
        self.message_type = kwargs.pop('message_type', 'reply')
        super(ComposeEmailForm, self).__init__(*args, **kwargs)

        # Only show the checkbox for existing attachments if we have a pk and if we forward.
        if 'initial' in kwargs and 'draft_pk' in kwargs['initial'] and self.message_type == 'forward':
            existing_attachment_list = EmailAttachment.objects.filter(
                message_id=kwargs['initial']['draft_pk'],
                inline=False
            )
            choices = [(attachment.id, attachment.name) for attachment in existing_attachment_list]
            self.fields['existing_attachments'] = forms.MultipleChoiceField(
                choices=choices,
                widget=forms.CheckboxSelectMultiple,
                initial=[a.id for a in existing_attachment_list],
                required=False,
            )

        self.fields['template'].queryset = EmailTemplate.objects.order_by('name')

        user = get_current_user()
        self.email_accounts = EmailAccount.objects.filter(
            Q(owner=user) |
            Q(shared_with_users=user) |
            Q(public=True)
        ).filter(tenant=user.tenant, is_deleted=False).distinct('id')

        # Only provide choices you have access to
        self.fields['send_from'].choices = [(email_account.id, email_account) for email_account in self.email_accounts]
        self.fields['send_from'].empty_label = None

        # Set user's primary_email as default choice if there is no initial value
        initial_email_account = self.initial.get('send_from', None)
        if not initial_email_account:
            if user.primary_email_account:
                initial_email_account = user.primary_email_account.id
            else:
                for email_account in self.email_accounts:
                    if email_account.email_address == user.email:
                        initial_email_account = email_account
                        break
        elif isinstance(initial_email_account, basestring):
            for email_account in self.email_accounts:
                if email_account.email == initial_email_account:
                    initial_email_account = email_account
                    break

        self.initial['send_from'] = initial_email_account
Esempio n. 32
0
    def post(self, request, *args, **kwargs):
        """
        Overloading post to update the assigned_to attribute for a Case object.
        """
        assignee = None

        try:
            assignee_id = request.POST.get('assignee', None)

            if assignee_id:
                # FIXME: WORKAROUND FOR TENANT FILTER.
                # An error will occur when using LilyUser.objects.all(), most likely because
                # the foreign key to contact (and maybe account) is filtered and executed before
                # the filter for the LilyUser. This way it's possible contacts (and maybe accounts)
                # won't be found for a user. But since it's a required field, an exception is raised.
                assignee = LilyUser.objects.get(pk=int(assignee_id), tenant=get_current_user().tenant.id)
        except LilyUser.DoesNotExist:
            messages.error(self.request, _('Assignee could not be changed'))
            raise Http404()

        try:
            case = Case.objects.get(pk=kwargs.pop('pk'))
        except Case.DoesNotExist:
            messages.error(self.request, _('Assignee could not be changed'))
            raise Http404()

        case.assigned_to = assignee
        case.save()

        if assignee:
            message = _('Assignee has been changed to %s') % assignee.full_name
            messages.success(self.request, message)
            # Return response
            return HttpResponse(anyjson.serialize({
                'assignee': {
                    'id': assignee.id,
                    'name': assignee.full_name,
                }
            }), content_type='application/json')
        else:
            message = _('Case has been unassigned')
            messages.success(self.request, message)
            # Return response
            return HttpResponse(anyjson.serialize({
                'assignee': None
            }), content_type='application/json')
Esempio n. 33
0
    def get(self, request, *args, **kwargs):
        account_id = kwargs.pop('account_id')

        try:
            email_account = EmailAccount.objects.get(pk=account_id)
        except EmailAccount.DoesNotExist:
            raise Http404()
        else:
            default_email_template_id = None

            try:
                current_user = get_current_user()
                default_email_template = email_account.default_templates.get(user_id=current_user.id)
                default_email_template_id = default_email_template.template.id
            except DefaultEmailTemplate.DoesNotExist:
                pass

            return HttpResponse(anyjson.serialize({
                'template_id': default_email_template_id,
            }), content_type='application/json')
Esempio n. 34
0
    def __init__(self, *args, **kwargs):
        super(CreateUpdateTemplateVariableForm, self).__init__(*args, **kwargs)

        try:
            if get_current_user() != self.instance.owner:
                self.fields['is_public'].widget = self.fields[
                    'is_public'].hidden_widget()
        except LilyUser.DoesNotExist:
            pass

        email_parameter_choices = get_email_parameter_choices()
        self.fields['variables'].choices += [
            [x, x] for x in email_parameter_choices.keys()
        ]

        for value in email_parameter_choices:
            for val in email_parameter_choices[value]:
                self.fields['values'].choices += [
                    [val, email_parameter_choices[value][val]],
                ]
Esempio n. 35
0
    def __init__(self, *args, **kwargs):
        self.message_type = kwargs.pop('message_type', 'reply')
        super(ComposeEmailForm, self).__init__(*args, **kwargs)

        if 'initial' in kwargs and 'draft_pk' in kwargs['initial']:
            if self.message_type is not 'reply':
                self.initial['attachments'] = EmailAttachment.objects.filter(
                    message_id=kwargs['initial']['draft_pk'],
                    inline=False
                )

        self.fields['template'].queryset = EmailTemplate.objects.order_by('name')

        user = get_current_user()
        self.email_accounts = EmailAccount.objects.filter(
            Q(owner=user) |
            Q(shared_with_users=user) |
            Q(public=True)
        ).filter(tenant=user.tenant, is_deleted=False).distinct('id')

        # Only provide choices you have access to
        self.fields['send_from'].choices = [(email_account.id, email_account) for email_account in self.email_accounts]
        self.fields['send_from'].empty_label = None

        # Set user's primary_email as default choice if there is no initial value
        initial_email_account = self.initial.get('send_from', None)
        if not initial_email_account:
            if user.primary_email_account:
                initial_email_account = user.primary_email_account.id
            else:
                for email_account in self.email_accounts:
                    if email_account.email_address == user.email:
                        initial_email_account = email_account
                        break
        elif isinstance(initial_email_account, basestring):
            for email_account in self.email_accounts:
                if email_account.email == initial_email_account:
                    initial_email_account = email_account
                    break

        self.initial['send_from'] = initial_email_account
Esempio n. 36
0
    def __init__(self, *args, **kwargs):
        self.message_type = kwargs.pop('message_type', 'reply')
        super(ComposeEmailForm, self).__init__(*args, **kwargs)

        if 'initial' in kwargs and 'draft_pk' in kwargs['initial']:
            if self.message_type is not 'reply':
                self.initial['attachments'] = EmailAttachment.objects.filter(
                    message_id=kwargs['initial']['draft_pk'],
                    inline=False
                )

        self.fields['template'].queryset = EmailTemplate.objects.order_by('name')

        user = get_current_user()
        self.email_accounts = EmailAccount.objects.filter(
            Q(owner=user) |
            Q(shared_with_users=user) |
            Q(public=True)
        ).filter(tenant=user.tenant, is_deleted=False).distinct('id')

        # Only provide choices you have access to
        self.fields['send_from'].choices = [(email_account.id, email_account) for email_account in self.email_accounts]
        self.fields['send_from'].empty_label = None

        # Set user's primary_email as default choice if there is no initial value
        initial_email_account = self.initial.get('send_from', None)
        if not initial_email_account:
            if user.primary_email_account:
                initial_email_account = user.primary_email_account.id
            else:
                for email_account in self.email_accounts:
                    if email_account.email_address == user.email:
                        initial_email_account = email_account
                        break
        elif isinstance(initial_email_account, basestring):
            for email_account in self.email_accounts:
                if email_account.email == initial_email_account:
                    initial_email_account = email_account
                    break

        self.initial['send_from'] = initial_email_account
Esempio n. 37
0
    def save(self, commit=True):
        default_for_data = self.cleaned_data.get('default_for')
        current_user = get_current_user()

        if commit:
            # Only save to db on commit
            for email_account in default_for_data:
                default_template, created = DefaultEmailTemplate.objects.get_or_create(
                    user=current_user,
                    account=email_account,
                    defaults={
                        'template': self.instance,
                    }
                )
                if not created:
                    # If default already exists, override the linked template and set to this one
                    default_template.template = self.instance
                    default_template.save()
            if not default_for_data:
                # There are no accounts submitted, delete previous defaults
                DefaultEmailTemplate.objects.filter(
                    user=current_user,
                    template=self.instance
                ).delete()
            else:
                # Delete defaults that were removed from selection
                account_id_list = []
                default_for_id_list = default_for_data.values_list('pk', flat=True)
                for email_account in self.initial.get('default_for'):
                    if email_account not in default_for_id_list:
                        account_id_list.append(email_account)

                DefaultEmailTemplate.objects.filter(
                    user=current_user,
                    template=self.instance,
                    account_id__in=account_id_list
                ).delete()

        return self.instance
Esempio n. 38
0
def has_required_tier(required_tier, tenant=None):
    """
    Check if the current payment plan has access to the feature.
    This is done by comparing the tenant's current tier with the required tier.

    Args:
        required_tier (int): The minimum required tier to access the feature.

    Returns:
        (boolean): Whether or not the tier requirement is met.
    """
    if not tenant:
        user = get_current_user()
        tenant = user.tenant

    if settings.BILLING_ENABLED:
        current_tier = tenant.billing.plan.tier

        return current_tier >= required_tier
    else:
        # Billing isn't enable so always return true.
        return True
Esempio n. 39
0
    def post(self, request, *args, **kwargs):
        """
        Overloading post to update the assigned_to attribute for a Case object.
        """
        assignee = None

        try:
            assignee_id = request.POST.get('assignee', None)

            if assignee_id:
                # FIXME: WORKAROUND FOR TENANT FILTER.
                # An error will occur when using LilyUser.objects.all(), most likely because
                # the foreign key to contact (and maybe account) is filtered and executed before
                # the filter for the LilyUser. This way it's possible contacts (and maybe accounts)
                # won't be found for a user. But since it's a required field, an exception is raised.
                assignee = LilyUser.objects.get(pk=int(assignee_id), tenant=get_current_user().tenant.id)
        except LilyUser.DoesNotExist:
            messages.error(self.request, _('Assignee could not be changed'))
            raise Http404()

        try:
            case = Case.objects.get(pk=kwargs.pop('pk'))
Esempio n. 40
0
    def save(self, commit=True):
        default_for_data = self.cleaned_data.get('default_for')
        current_user = get_current_user()

        if commit:
            # Only save to db on commit
            for email_account in default_for_data:
                default_template, created = DefaultEmailTemplate.objects.get_or_create(
                    user=current_user,
                    account=email_account,
                    defaults={
                        'template': self.instance,
                    }
                )
                if not created:
                    # If default already exists, override the linked template and set to this one
                    default_template.template = self.instance
                    default_template.save()
            if not default_for_data:
                # There are no accounts submitted, delete previous defaults
                DefaultEmailTemplate.objects.filter(
                    user=current_user,
                    template=self.instance
                ).delete()
            else:
                # Delete defaults that were removed from selection
                account_id_list = []
                default_for_id_list = default_for_data.values_list('pk', flat=True)
                for email_account in self.initial.get('default_for'):
                    if email_account not in default_for_id_list:
                        account_id_list.append(email_account)

                DefaultEmailTemplate.objects.filter(
                    user=current_user,
                    template=self.instance,
                    account_id__in=account_id_list
                ).delete()

        return self.instance
Esempio n. 41
0
    def save(self, commit=True):
        """
        Check for parcel information and store in separate model
        """
        if not self.instance.id:
            self.instance.created_by = get_current_user()

        instance = super(CreateUpdateCaseForm, self).save(commit=commit)

        # Add parcel information
        if self.cleaned_data['parcel_identifier'] and self.cleaned_data[
                'parcel_provider']:
            # There is parcel information stored
            if instance.parcel:
                # Update
                instance.parcel.provider = self.cleaned_data['parcel_provider']
                instance.parcel.identifier = self.cleaned_data[
                    'parcel_identifier']
            else:
                # Create
                parcel = Parcel(
                    provider=self.cleaned_data['parcel_provider'],
                    identifier=self.cleaned_data['parcel_identifier'])
                if commit:
                    parcel.save()
                instance.parcel = parcel
        elif instance.parcel:
            # Remove parcel
            instance.parcel = None

        # If archived, set status to last position
        if instance.is_archived:
            instance.status = CaseStatus.objects.last()

        if commit:
            instance.save()

        return instance
Esempio n. 42
0
    def get(self, request, *args, **kwargs):
        account_id = kwargs.pop('account_id')

        try:
            email_account = EmailAccount.objects.get(pk=account_id)
        except EmailAccount.DoesNotExist:
            raise Http404()
        else:
            default_email_template_id = None

            try:
                current_user = get_current_user()
                default_email_template = email_account.default_templates.get(
                    user_id=current_user.id)
                default_email_template_id = default_email_template.template.id
            except DefaultEmailTemplate.DoesNotExist:
                pass

            return HttpResponse(anyjson.serialize({
                'template_id':
                default_email_template_id,
            }),
                                content_type='application/json')
Esempio n. 43
0
    def save(self, commit=True):
        """
        Check for parcel information and store in separate model
        """
        if not self.instance.id:
            self.instance.created_by = get_current_user()

        instance = super(CreateUpdateCaseForm, self).save(commit=commit)

        # Add parcel information
        if self.cleaned_data['parcel_identifier'] and self.cleaned_data['parcel_provider']:
            # There is parcel information stored
            if instance.parcel:
                # Update
                instance.parcel.provider = self.cleaned_data['parcel_provider']
                instance.parcel.identifier = self.cleaned_data['parcel_identifier']
            else:
                # Create
                parcel = Parcel(
                    provider=self.cleaned_data['parcel_provider'],
                    identifier=self.cleaned_data['parcel_identifier']
                )
                if commit:
                    parcel.save()
                instance.parcel = parcel
        elif instance.parcel:
            # Remove parcel
            instance.parcel = None

        # If archived, set status to last position
        if instance.is_archived:
            instance.status = CaseStatus.objects.last()

        if commit:
            instance.save()

        return instance
Esempio n. 44
0
    def get(self, request, *args, **kwargs):
        template = EmailTemplate.objects.get(pk=kwargs.get('template_id'))
        lookup = {'user': self.request.user}

        if 'account_id' in self.request.GET:
            try:
                account = Account.objects.get(pk=self.request.GET.get('account_id'))
            except Account.DoesNotExist:
                pass
            else:
                lookup.update({'account': account})

        if 'contact_id' in self.request.GET:
            try:
                contact = Contact.objects.get(pk=self.request.GET.get('contact_id'))
            except Contact.DoesNotExist:
                pass
            else:
                lookup.update({'contact': contact})
                functions = contact.functions.all()
                if len(functions) == 1:
                    try:
                        account = Account.objects.get(pk=functions[0].account_id)
                    except Account.DoesNotExist:
                        pass
                    else:
                        lookup.update({'account': account})

        if 'document_id' in self.request.GET:
            credentials = get_credentials(IntegrationDetails.PANDADOC)

            document_id = self.request.GET.get('document_id')
            recipient = self.request.GET.get('recipient_email')

            # Set the status of the document to 'sent' so we can create a view session.
            send_url = 'https://api.pandadoc.com/public/v1/documents/%s/send' % document_id
            send_params = {'silent': True}

            response = send_post_request(send_url, credentials, send_params)

            session_url = 'https://api.pandadoc.com/public/v1/documents/%s/session' % document_id
            year = 60 * 60 * 24 * 365
            session_params = {'recipient': recipient, 'lifetime': year}

            response = send_post_request(session_url, credentials, session_params)

            if response.status_code == 201:
                sign_url = 'https://app.pandadoc.com/s/%s' % response.json().get('id')
                lookup.update({'document': {'sign_url': sign_url}})

        if 'emailaccount_id' in self.request.GET:
            try:
                emailaccount = EmailAccount.objects.get(pk=self.request.GET.get('emailaccount_id'))
            except EmailAccount.DoesNotExist:
                pass
            else:
                lookup.get('user').current_email_address = emailaccount.email_address

        # Setup regex to find custom variables
        search_regex = '\[\[ custom\.(.*?) \]\]'
        # Find all occurrences.
        search_result = re.findall(search_regex, template.body_html)

        if search_result:
            for custom_variable in search_result:
                public = None

                try:
                    # Try to split to see if it's a public variable
                    variable, public = custom_variable.split('.')
                except ValueError:
                    # Not a public variable, so .split raises an error
                    variable = custom_variable

                if public:
                    template_variable = TemplateVariable.objects.filter(
                        name__iexact=variable,
                        is_public=True
                    )
                else:
                    template_variable = TemplateVariable.objects.filter(
                        name__iexact=variable,
                        owner=get_current_user()
                    )

                if template_variable:
                    # find = '\[\[ custom.' + custom_variable + '(\s)?\]\]'
                    find = re.compile('\[\[ custom\.' + custom_variable + ' \]\]')
                    replace = template_variable.first().text

                    template.body_html = re.sub(find, replace, template.body_html, 1)

        # Ugly hack to make parsing of new template brackets style work
        parsed_template = Template(template.body_html.replace('[[', '{{').replace(']]', '}}')).render(Context(lookup))
        parsed_subject = Template(template.subject.replace('[[', '{{').replace(']]', '}}')).render(Context(lookup))

        # Make sure HTML entities are displayed correctly
        html_parser = HTMLParser.HTMLParser()
        parsed_subject = html_parser.unescape(parsed_subject)

        attachments = []

        for attachment in template.attachments.all():
            # Get attachment name
            name = get_attachment_filename_from_url(attachment.attachment.name)

            attachments.append({
                'id': attachment.id,
                'name': name,
            })

        return HttpResponse(anyjson.serialize({
            'template': parsed_template,
            'template_subject': parsed_subject,
            'attachments': attachments,
        }), content_type='application/json')
Esempio n. 45
0
    def get(self, request, *args, **kwargs):
        template = EmailTemplate.objects.get(pk=kwargs.get('template_id'))
        lookup = {'user': self.request.user}

        if 'account_id' in self.request.GET:
            try:
                account = Account.objects.get(pk=self.request.GET.get('account_id'))
            except Account.DoesNotExist:
                pass
            else:
                lookup.update({'account': account})

        if 'contact_id' in self.request.GET:
            try:
                contact = Contact.objects.get(pk=self.request.GET.get('contact_id'))
            except Contact.DoesNotExist:
                pass
            else:
                lookup.update({'contact': contact})
                functions = contact.functions.all()
                if len(functions) == 1:
                    try:
                        account = Account.objects.get(pk=functions[0].account_id)
                    except Account.DoesNotExist:
                        pass
                    else:
                        lookup.update({'account': account})

        if 'emailaccount_id' in self.request.GET:
            try:
                emailaccount = EmailAccount.objects.get(pk=self.request.GET.get('emailaccount_id'))
            except EmailAccount.DoesNotExist:
                pass
            else:
                lookup.get('user').current_email_address = emailaccount.email_address

        # Setup regex to find custom variables
        search_regex = '\[\[ custom\.(.*?) \]\]'
        # Find all occurences
        search_result = re.findall(search_regex, template.body_html)

        if search_result:
            for custom_variable in search_result:
                public = None

                try:
                    # Try to split to see if it's a public variable
                    variable, public = custom_variable.split('.')
                except ValueError:
                    # Not a public variable, so .split raises an error
                    variable = custom_variable

                if public:
                    template_variable = TemplateVariable.objects.filter(name__iexact=variable, is_public=True)
                else:
                    template_variable = TemplateVariable.objects.filter(name__iexact=variable, owner=get_current_user())

                if template_variable:
                    # find = '\[\[ custom.' + custom_variable + '(\s)?\]\]'
                    find = re.compile('\[\[ custom\.' + custom_variable + ' \]\]')
                    replace = template_variable.first().text

                    template.body_html = re.sub(find, replace, template.body_html, 1)

        # Ugly hack to make parsing of new template brackets style work
        parsed_template = Template(template.body_html.replace('[[', '{{').replace(']]', '}}')).render(Context(lookup))
        parsed_subject = Template(template.subject.replace('[[', '{{').replace(']]', '}}')).render(Context(lookup))

        attachments = []

        for attachment in template.attachments.all():
            # Get attachment name
            name = get_attachment_filename_from_url(attachment.attachment.name)

            attachments.append({
                'id': attachment.id,
                'name': name,
            })

        return HttpResponse(anyjson.serialize({
            'template': parsed_template,
            'template_subject': parsed_subject,
            'attachments': attachments,
        }), content_type='application/json')
Esempio n. 46
0
    def clean(self):
        cleaned_data = super(CreateUpdateTemplateVariableForm, self).clean()

        queryset = TemplateVariable.objects.filter(name__iexact=cleaned_data.get('name'), owner=get_current_user())

        # Check if variable already exists, but only when creating a new one
        if self.instance:
            queryset = queryset.exclude(id=self.instance.id)
        if queryset.exists():
            self._errors['name'] = ['Template variable with that name already exists for this user']

        return cleaned_data
Esempio n. 47
0
    def get(self, request, *args, **kwargs):
        template = EmailTemplate.objects.get(pk=kwargs.get('template_id'))
        lookup = {'user': self.request.user}

        if 'account_id' in self.request.GET:
            try:
                account = Account.objects.get(
                    pk=self.request.GET.get('account_id'))
            except Account.DoesNotExist:
                pass
            else:
                lookup.update({'account': account})

        if 'contact_id' in self.request.GET:
            try:
                contact = Contact.objects.get(
                    pk=self.request.GET.get('contact_id'))
            except Contact.DoesNotExist:
                pass
            else:
                lookup.update({'contact': contact})
                functions = contact.functions.all()
                if len(functions) == 1:
                    try:
                        account = Account.objects.get(
                            pk=functions[0].account_id)
                    except Account.DoesNotExist:
                        pass
                    else:
                        lookup.update({'account': account})

        if 'emailaccount_id' in self.request.GET:
            try:
                emailaccount = EmailAccount.objects.get(
                    pk=self.request.GET.get('emailaccount_id'))
            except EmailAccount.DoesNotExist:
                pass
            else:
                lookup.get(
                    'user').current_email_address = emailaccount.email_address

        # Setup regex to find custom variables
        search_regex = '\[\[ custom\.(.*?) \]\]'
        # Find all occurences
        search_result = re.findall(search_regex, template.body_html)

        if search_result:
            for custom_variable in search_result:
                public = None

                try:
                    # Try to split to see if it's a public variable
                    variable, public = custom_variable.split('.')
                except ValueError:
                    # Not a public variable, so .split raises an error
                    variable = custom_variable

                if public:
                    template_variable = TemplateVariable.objects.filter(
                        name__iexact=variable, is_public=True)
                else:
                    template_variable = TemplateVariable.objects.filter(
                        name__iexact=variable, owner=get_current_user())

                if template_variable:
                    # find = '\[\[ custom.' + custom_variable + '(\s)?\]\]'
                    find = re.compile('\[\[ custom\.' + custom_variable +
                                      ' \]\]')
                    replace = template_variable.first().text

                    template.body_html = re.sub(find, replace,
                                                template.body_html, 1)

        # Ugly hack to make parsing of new template brackets style work
        parsed_template = Template(
            template.body_html.replace('[[', '{{').replace(']]', '}}')).render(
                Context(lookup))
        parsed_subject = Template(
            template.subject.replace('[[', '{{').replace(']]', '}}')).render(
                Context(lookup))

        attachments = []

        for attachment in template.attachments.all():
            # Get attachment name
            name = get_attachment_filename_from_url(attachment.attachment.name)

            attachments.append({
                'id': attachment.id,
                'name': name,
            })

        return HttpResponse(anyjson.serialize({
            'template': parsed_template,
            'template_subject': parsed_subject,
            'attachments': attachments,
        }),
                            content_type='application/json')
Esempio n. 48
0
    def _create_object(self, **kwargs):
        if 'send_from__owner' not in kwargs:
            kwargs['send_from__owner'] = get_current_user()

        return super(DraftEmailTests, self)._create_object(**kwargs)
Esempio n. 49
0
    def save(self, *args, **kwargs):
        user = get_current_user()
        if user and user.is_authenticated():
            self.tenant = user.tenant

        return super(MultiTenantMixin, self).save(*args, **kwargs)
Esempio n. 50
0
 def get_queryset(self):
     queryset = self.queryset.filter(tenant=get_current_user().tenant)
     return queryset
Esempio n. 51
0
    def _create_object(self, **kwargs):
        if 'send_from__owner' not in kwargs:
            kwargs['send_from__owner'] = get_current_user()

        return super(DraftEmailTests, self)._create_object(**kwargs)
Esempio n. 52
0
 def get_queryset(self):
     queryset = self.queryset.filter(tenant=get_current_user().tenant)
     return queryset
Esempio n. 53
0
    def get(self, request, *args, **kwargs):
        template = EmailTemplate.objects.get(pk=kwargs.get('template_id'))
        lookup = {'user': self.request.user}
        errors = {}

        if 'account_id' in self.request.GET:
            try:
                account = Account.objects.get(
                    pk=self.request.GET.get('account_id'))
            except Account.DoesNotExist:
                pass
            else:
                lookup.update({'account': account})

        if 'contact_id' in self.request.GET:
            try:
                contact = Contact.objects.get(
                    pk=self.request.GET.get('contact_id'))
            except Contact.DoesNotExist:
                pass
            else:
                lookup.update({'contact': contact})
                functions = contact.functions.all()
                if len(functions) == 1:
                    try:
                        account = Account.objects.get(
                            pk=functions[0].account_id)
                    except Account.DoesNotExist:
                        pass
                    else:
                        lookup.update({'account': account})

        if 'document_id' in self.request.GET:
            credentials = get_credentials('pandadoc')

            if credentials:
                error_message = None
                document_id = self.request.GET.get('document_id')
                recipient = self.request.GET.get('recipient_email')

                details_url = 'https://api.pandadoc.com/public/v1/documents/%s/details' % document_id

                response = send_get_request(details_url, credentials)

                if response.status_code == 200:
                    # Only documents with the 'draft' status can be set to sent.
                    if response.json().get('status') == 'document.draft':
                        # Set the status of the document to 'sent' so we can create a view session.
                        send_url = 'https://api.pandadoc.com/public/v1/documents/%s/send' % document_id
                        send_params = {'silent': True}
                        response = send_post_request(send_url, credentials,
                                                     send_params)

                        if response.status_code != 200:
                            error_message = 'Something went wrong while setting up the PandaDoc sign URL.'

                    metadata = response.json().get('metadata')

                    if metadata and metadata.get('account'):
                        account_id = metadata.get('account')

                        try:
                            account = Account.objects.get(pk=account_id)
                        except Account.DoesNotExist:
                            pass
                        else:
                            lookup.update({'account': account})

                    # Document has been 'sent' so create the session.
                    session_url = 'https://api.pandadoc.com/public/v1/documents/%s/session' % document_id
                    year = 60 * 60 * 24 * 365
                    session_params = {'recipient': recipient, 'lifetime': year}

                    response = send_post_request(session_url, credentials,
                                                 session_params)

                    if response.status_code == 201:
                        sign_url = 'https://app.pandadoc.com/s/%s' % response.json(
                        ).get('id')
                        lookup.update({'document': {'sign_url': sign_url}})
                    else:
                        error_message = (
                            'The PandaDoc sign URL could not be created \
                                          because the recipient isn\'t correct'
                        )
                else:
                    error_message = 'The document doesn\'t seem to be valid.'

                if error_message:
                    errors.update({'document': error_message})

        if 'emailaccount_id' in self.request.GET:
            try:
                emailaccount = EmailAccount.objects.get(
                    pk=self.request.GET.get('emailaccount_id'))
            except EmailAccount.DoesNotExist:
                pass
            else:
                lookup.get(
                    'user').current_email_address = emailaccount.email_address

        # Setup regex to find custom variables
        search_regex = '\[\[ custom\.(.*?) \]\]'
        # Find all occurrences.
        search_result = re.findall(search_regex, template.body_html)

        if search_result:
            for custom_variable in search_result:
                public = None

                try:
                    # Try to split to see if it's a public variable
                    variable, public = custom_variable.split('.')
                except ValueError:
                    # Not a public variable, so .split raises an error
                    variable = custom_variable

                if public:
                    template_variable = TemplateVariable.objects.filter(
                        name__iexact=variable, is_public=True)
                else:
                    template_variable = TemplateVariable.objects.filter(
                        name__iexact=variable, owner=get_current_user())

                if template_variable:
                    # find = '\[\[ custom.' + custom_variable + '(\s)?\]\]'
                    find = re.compile('\[\[ custom\.' + custom_variable +
                                      ' \]\]')
                    replace = template_variable.first().text

                    template.body_html = re.sub(find, replace,
                                                template.body_html, 1)

        # Ugly hack to make parsing of new template brackets style work
        parsed_template = Template(
            template.body_html.replace('[[', '{{').replace(']]', '}}')).render(
                Context(lookup))
        parsed_subject = Template(
            template.subject.replace('[[', '{{').replace(']]', '}}')).render(
                Context(lookup))

        # Make sure HTML entities are displayed correctly
        html_parser = HTMLParser.HTMLParser()
        parsed_subject = html_parser.unescape(parsed_subject)

        attachments = []

        for attachment in template.attachments.all():
            # Get attachment name
            name = get_attachment_filename_from_url(attachment.attachment.name)

            attachments.append({
                'id': attachment.id,
                'name': name,
            })

        return HttpResponse(anyjson.serialize({
            'template': parsed_template,
            'template_subject': parsed_subject,
            'attachments': attachments,
            'errors': errors,
        }),
                            content_type='application/json')