Send jnf response as pdf attachment (#107)

* Attach jnf response pdf after verifying email.

* add pdfkit to requirments.txt
This commit is contained in:
karthik mv 2022-05-02 12:43:26 +05:30 committed by GitHub
parent 40e2075617
commit f38f013cee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 106 additions and 25 deletions

View File

@ -260,36 +260,21 @@ def verifyEmail(request):
if send_email_to_company:
# Email sending part.
details = model_to_dict(opening, fields=[field.name for field in Placement._meta.fields],
exclude=['id', 'is_company_details_pdf', 'offer_accepted', 'is_description_pdf',
'is_compensation_details_pdf', 'is_selection_procedure_details_pdf',
'email_verified'])
keys = list(details.keys())
newdetails = {}
for key in keys:
if isinstance(details[key], list):
details[key] = {"details": details[key], "type": ["list"]}
if key in ['website', 'company_details_pdf_names', 'description_pdf_names',
'compensation_details_pdf_names', 'selection_procedure_pdf_names']:
if key == 'website':
details[key] = {"details": details[key], "type": ["link"]}
else:
details[key] = {"details": details[key]["details"], "type": ["list", "link"],
"link": LINK_TO_STORAGE_COMPANY_ATTACHMENT + opening.id + "/"}
new_key = key.replace('_', ' ')
if key == 'company_details_pdf_names':
new_key = 'company details pdf'
newdetails[new_key] = details[key]
pdfhtml = opening_description_table_html(opening)
name = opening.company_name + '_jnf_response.pdf'
attachment_jnf_respone = {
"name": name,
"html": pdfhtml,
}
data = {
"designation": opening.designation,
"opening_type": PLACEMENT,
"opening_link": PLACEMENT_OPENING_URL.format(id=opening.id), # Some Changes here too
"company_name": opening.company_name,
"data": newdetails
}
json_data = json.dumps(data, default=str)
sendEmail(opening.email, COMPANY_OPENING_SUBMITTED_TEMPLATE_SUBJECT.format(id=opening.id), json_data,
COMPANY_OPENING_SUBMITTED_TEMPLATE)
COMPANY_OPENING_SUBMITTED_TEMPLATE, attachment_jnf_respone)
return Response({'action': "Verify Email", 'message': "Email Verified Successfully"},
status=status.HTTP_200_OK)

View File

@ -134,6 +134,9 @@ COMPANY_OPENING_SUBMITTED_TEMPLATE = 'company_opening_submitted.html'
STUDENT_APPLICATION_STATUS_SELECTED_TEMPLATE = 'student_application_status_selected.html'
STUDENT_APPLICATION_STATUS_NOT_SELECTED_TEMPLATE = 'student_application_status_not_selected.html'
COMPANY_EMAIL_VERIFICATION_TEMPLATE = 'company_email_verification.html'
COMPANY_JNF_RESPONSE_TEMPLATE = 'company_jnf_response.html'
APPLICATION_CSV_COL_NAMES = ['Applied At', 'Roll No.', 'Name', 'Email', 'Phone Number', 'Branch', 'Batch', 'CPI',
'Resume', 'Selected', ]
PDF_FILES_SERVING_ENDPOINT = 'http://localhost:5500/CDC_Backend/Storage/Company_Attachments/' # TODO: Change this to actual URL

View File

@ -12,6 +12,7 @@ import background_task
import jwt
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.forms.models import model_to_dict
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
@ -21,9 +22,10 @@ from google.oauth2 import id_token
from rest_framework import status
from rest_framework.response import Response
import requests as rq
import pdfkit
from .constants import *
from .models import User, PrePlacementOffer, PlacementApplication
from .models import User, PrePlacementOffer, PlacementApplication, Placement
logger = logging.getLogger('db')
@ -134,7 +136,7 @@ def saveFile(file, location):
@background_task.background(schedule=10)
def sendEmail(email_to, subject, data, template):
def sendEmail(email_to, subject, data, template, attachment_jnf_respone=None):
try:
if not isinstance(data, dict):
data = json.loads(data)
@ -146,6 +148,10 @@ def sendEmail(email_to, subject, data, template):
msg = EmailMultiAlternatives(subject, text_content, email_from, recipient_list)
msg.attach_alternative(html_content, "text/html")
if attachment_jnf_respone:
logger.info(attachment_jnf_respone)
pdf = pdfkit.from_string(attachment_jnf_respone['html'], False,options={"--enable-local-file-access": "",'--dpi':'96'})
msg.attach(attachment_jnf_respone['name'], pdf, 'application/pdf')
msg.send()
return True
except:
@ -262,3 +268,28 @@ def verify_recaptcha(request):
print(traceback.format_exc())
logger.warning("Utils - verify_recaptcha: " + str(sys.exc_info()))
return False, "_"
def opening_description_table_html(opening):
details = model_to_dict(opening, fields = [field.name for field in Placement._meta.fields], exclude = ['id','is_company_details_pdf','offer_accepted','is_description_pdf','is_compensation_details_pdf','is_selection_procedure_details_pdf','email_verified'])
keys = list(details.keys())
newdetails = {}
for key in keys:
if isinstance(details[key], list):
details[key] = {"details": details[key], "type": ["list"]}
if key in ['website','company_details_pdf_names','description_pdf_names','compensation_details_pdf_names','selection_procedure_pdf_names']:
if key == 'website':
details[key] = {"details": details[key], "type": ["link"]}
else:
details[key] = {"details": details[key]["details"], "type": ["list","link"], "link": PDF_FILES_SERVING_ENDPOINT+opening.id+"/"}
new_key = key.replace('_',' ')
if key.endswith(' names'):
new_key = key[:-6]
new_key = new_key.capitalize()
newdetails[new_key] = details[key]
imagepath = os.path.abspath('./templates/image.png')
print(imagepath)
data = {
"data": newdetails,
"imgpath": imagepath
}
return render_to_string(COMPANY_JNF_RESPONSE_TEMPLATE, data)

View File

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#details_table tr:nth-child(even) {background: #FFF}
#details_table tr:nth-child(odd) {background: #bfe3f3}
#details_table td {padding: 10px; width: 50%;}
#details_table{
border: #334878 1px solid;
border-collapse: collapse;
width: 80%;
margin:auto;
}
</style>
<title>Document</title>
</head>
<body style="margin: 0;">
<header style="background-color: #334878;"><img style="height: 3cm; margin: auto; display: block; padding: 0.5cm;" src='{{imgpath}}' alt="cdc logo"></header>
<h1 style="text-align: center;"> Job Notification Form Response</h1>
<table id="details_table">
{% for key, value in data.items %}
<tr>
<td >
{{ key }}
</td>
<td>
{% if 'list' in value.type %}
{% for item in value.details %}
<li>
{% if 'link' in value.type and value.link %}
<a href="{{value.link|add:item}}">{{ item }}</a>
{% elif 'link' in value.type %}
<a href="{{item}}">{{ item }}</a>
{% else %}
{{ item }}
{% endif %}
</li>
{% endfor %}
{% else %}
{% if 'link' in value.type %}
<a href="{{ value.details }}">{{ value.details }}</a>
{% else %}
{{ value }}
{% endif %}
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<p style="margin-left: 10%;">In case of any descripency regarding above details, please contact <a href="mailto:cdc@iitdh.ac.in">cdc@iitdh.ac.in</a>
</p>
</body>
</html>

View File

@ -21,6 +21,7 @@ jsonfield==3.1.0
lazy-object-proxy==1.6.0
Markdown==3.3.6
mccabe==0.7.0
pdfkit==1.0.0
platformdirs==2.5.1
psycopg2-binary==2.9.3
pyasn1==0.4.8