added action endpoint for emailing company manager

This commit is contained in:
Sam
2021-02-05 13:53:55 +00:00
parent a9cb7cedd6
commit 39f6a8bcfb
3 changed files with 37 additions and 1 deletions

View File

@@ -1,11 +1,15 @@
import logging
from django.shortcuts import render from django.shortcuts import render
from django.core import serializers from django.core import serializers
from rest_framework.decorators import api_view, permission_classes from django.core.mail import EmailMessage
from django.template.loader import render_to_string
# Create your views here. # Create your views here.
from rest_framework import viewsets from rest_framework import viewsets
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
from companies.models import Company from companies.models import Company
from companies.serializers import CompanySerializer from companies.serializers import CompanySerializer
@@ -21,6 +25,37 @@ class CompanyViewSet(viewsets.ModelViewSet):
def perform_create(self, serializer): def perform_create(self, serializer):
serializer.save(creator=self.request.user) serializer.save(creator=self.request.user)
@action(detail=True, methods=['POST', ])
def email_manager(self, request, **kwargs):
"""
Send email to company.creator
"""
queryset = self.get_custom_queryset(request)
instance = queryset.filter(pk=kwargs['pk']).first()
if instance:
data = json.loads(request.body)
# send email to manager
message = render_to_string('company_contact.html', {
'user': request.user,
'data': data,
})
email = EmailMessage(subject, message, to=[instance.creator.email])
email.send()
logging.info(f"Email sent to {instance.creator.email} as manager of {instance.name}")
# send confirmation email to user
message = render_to_string('confirm_company_contact.html', {
'user': request.user,
})
email = EmailMessage(subject, message, to=[request.user.email])
email.send()
logging.info(f"Confirmation email sent to {request.user.email}")
return Response(data=data)
else:
return Response({"errors":{"details": f"No instance of company with id {kwargs['pk']}",}})
@api_view(['GET',]) @api_view(['GET',])
@permission_classes([IsAuthenticated,]) @permission_classes([IsAuthenticated,])
@@ -28,3 +63,4 @@ def my_company(request):
qs = Company.objects.filter(creator=request.user) qs = Company.objects.filter(creator=request.user)
data = serializers.serialize('json', qs) data = serializers.serialize('json', qs)
return Response(data=data) return Response(data=data)

View File

View File