Merge branch 'main' into add-migrations

This commit is contained in:
karthik mv 2023-12-01 02:41:10 +05:30 committed by GitHub
commit c31ac2e6f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 114 additions and 26 deletions

View File

@ -124,7 +124,7 @@ def updateDeadline(request, id, email, user_type):
opening.deadline_datetime = datetime.datetime.strptime(data[DEADLINE_DATETIME], '%Y-%m-%d %H:%M:%S %z') opening.deadline_datetime = datetime.datetime.strptime(data[DEADLINE_DATETIME], '%Y-%m-%d %H:%M:%S %z')
opening.changed_by = get_object_or_404(User, id=id) opening.changed_by = get_object_or_404(User, id=id)
opening.save() opening.save()
send_opening_to_notifications_service(id=opening.id,name=opening.company_name,deadline=data[DEADLINE_DATETIME],role=opening.designation) send_opening_to_notifications_service(id=opening.id,name=opening.company_name,deadline=data[DEADLINE_DATETIME],role=opening.designation,opening_type=opening_type)
return Response({'action': "Update Deadline", 'message': "Deadline Updated"}, return Response({'action': "Update Deadline", 'message': "Deadline Updated"},
status=status.HTTP_200_OK) status=status.HTTP_200_OK)
except Http404: except Http404:
@ -162,7 +162,7 @@ def updateOfferAccepted(request, id, email, user_type):
opening.save() opening.save()
if opening.offer_accepted: if opening.offer_accepted:
deadline=deadline_datetime.strftime('%Y-%m-%d %H:%M:%S %z') deadline=deadline_datetime.strftime('%Y-%m-%d %H:%M:%S %z')
send_opening_to_notifications_service(id=opening.id,name=opening.company_name,deadline=deadline,role=opening.designation) send_opening_to_notifications_service(id=opening.id,name=opening.company_name,deadline=deadline,role=opening.designation,opening_type=opening_type)
send_opening_notifications(opening.id,opening_type) send_opening_notifications(opening.id,opening_type)
else: else:
raise ValueError("Offer Status already updated") raise ValueError("Offer Status already updated")
@ -767,7 +767,11 @@ def get_eligible_students(request):
opening_type= data[OPENING_TYPE] opening_type= data[OPENING_TYPE]
else: else:
opening_type= "Placement" opening_type= "Placement"
eligible_students=get_eligible_emails(opening_id=opening_id, opening_type=opening_type) if "send_all" in data:
send_all = "True"==data["send_all"]
else:
send_all = False
eligible_students=get_eligible_emails(opening_id=opening_id, opening_type=opening_type, send_all=send_all)
return Response({'action': "Get Eligible Students", 'message': "Eligible Students Fetched", return Response({'action': "Get Eligible Students", 'message': "Eligible Students Fetched",
'eligible_students': eligible_students}, 'eligible_students': eligible_students},
status=status.HTTP_200_OK) status=status.HTTP_200_OK)

View File

@ -17,6 +17,8 @@ logger = logging.getLogger('db')
RECAPTCHA_VALUE, JOB_LOCATION RECAPTCHA_VALUE, JOB_LOCATION
]) ])
def addPlacement(request): def addPlacement(request):
logger.info("JNF filled by " + str(request.data['email']))
logger.info(request.data)
try: try:
data = request.data data = request.data
files = request.FILES files = request.FILES
@ -233,14 +235,14 @@ def addPlacement(request):
except ValueError as e: except ValueError as e:
store_all_files(request) store_all_files(request)
exception_email(data) #exception_email(data)
logger.warning("ValueError in addPlacement: " + str(e)) logger.warning("ValueError in addPlacement: " + str(e))
logger.warning(traceback.format_exc()) logger.warning(traceback.format_exc())
return Response({'action': "Add Placement", 'message': str(e)}, return Response({'action': "Add Placement", 'message': str(e)},
status=status.HTTP_400_BAD_REQUEST) status=status.HTTP_400_BAD_REQUEST)
except: except:
store_all_files(request) store_all_files(request)
exception_email(data) #exception_email(data)
logger.warning("Add New Placement: " + str(sys.exc_info())) logger.warning("Add New Placement: " + str(sys.exc_info()))
logger.warning(traceback.format_exc()) logger.warning(traceback.format_exc())
return Response({'action': "Add Placement", 'message': "Something went wrong"}, return Response({'action': "Add Placement", 'message': "Something went wrong"},
@ -353,6 +355,7 @@ def autoFillInf(request):
CONTACT_PERSON_NAME, PHONE_NUMBER, EMAIL, RECAPTCHA_VALUE]) CONTACT_PERSON_NAME, PHONE_NUMBER, EMAIL, RECAPTCHA_VALUE])
def addInternship(request): def addInternship(request):
logger.info("INF filled by " + str(request.data['email'])) logger.info("INF filled by " + str(request.data['email']))
logger.info(request.data)
try: try:
data = request.data data = request.data
files = request.FILES files = request.FILES
@ -416,12 +419,13 @@ def addInternship(request):
else: else:
internship.is_work_from_home = False internship.is_work_from_home = False
if data[ALLOWED_BATCH] is None or json.loads(data[ALLOWED_BATCH]) == "": if ALLOWED_BATCH in data and (data[ALLOWED_BATCH] is None or json.loads(data[ALLOWED_BATCH]) == ""):
raise ValueError('Allowed Branch cannot be empty') raise ValueError('Allowed Batches cannot be empty')
elif set(json.loads(data[ALLOWED_BATCH])).issubset(BATCHES): elif ALLOWED_BATCH in data and set(json.loads(data[ALLOWED_BATCH])).issubset(BATCHES):
internship.allowed_batch = json.loads(data[ALLOWED_BATCH]) internship.allowed_batch = json.loads(data[ALLOWED_BATCH])
else: else:
raise ValueError('Allowed Batch must be a subset of ' + str(BATCHES)) internship.allowed_batch = ['2021']
if data[ALLOWED_BRANCH] is None or json.loads(data[ALLOWED_BRANCH]) == "": if data[ALLOWED_BRANCH] is None or json.loads(data[ALLOWED_BRANCH]) == "":
raise ValueError('Allowed Branch cannot be empty') raise ValueError('Allowed Branch cannot be empty')

63
CDC_Backend/APIs/cron.py Normal file
View File

@ -0,0 +1,63 @@
from .models import *
from .utils import *
import shutil
import logging
import traceback
logger=logging.getLogger('db')
def clean_up_tests():
# Delete all the test internships and placements created
try:
internships= Internship.objects.filter(company_name="test company",email="notifications@cdc-iitdh.tech")
hits_internship=len(internships)
for internship in internships:
#count number of file
files = os.listdir(STORAGE_DESTINATION_COMPANY_ATTACHMENTS+internship.id)
if len(files) == 4:
print("working fine")
else:
print("not working fine")
logger.error("files submitted in inf are not getting stored for test case"+internship.description)
#remove folder from the server
print("removing folder ",STORAGE_DESTINATION_COMPANY_ATTACHMENTS+internship.id)
shutil.rmtree(STORAGE_DESTINATION_COMPANY_ATTACHMENTS+internship.id)
internship.delete()
placements= Placement.objects.filter(company_name="test company",email="notifications@cdc-iitdh.tech")
hits_placement=len(placements)
for placement in placements:
#count number of file
files = os.listdir(STORAGE_DESTINATION_COMPANY_ATTACHMENTS+placement.id)
if len(files) == 4:
print("working fine")
else:
print("not working fine")
logger.error("files submitted in inf are not getting stored for test case"+placement.description)
#remove folder from the server
print("removing folder ",STORAGE_DESTINATION_COMPANY_ATTACHMENTS+internship.id)
shutil.rmtree(STORAGE_DESTINATION_COMPANY_ATTACHMENTS+placement.id)
placement.delete()
if hits_internship >= 6:
print("all hits are working fine")
else:
print("some hits are not working fine")
logger.error("some test hits are not working fine for internship")
if hits_placement >= 6:
print("all hits are working fine")
else:
print("some hits are not working fine")
logger.error("some test hits are not working fine for placement")
except :
logger.error("error in clean up function")
logger.error(traceback.format_exc())

View File

@ -214,14 +214,16 @@ def sendEmail(email_to, subject, data, template, attachment_jnf_response=None):
else: else:
recipient_list = [str(email_to), ] recipient_list = [str(email_to), ]
msg = EmailMultiAlternatives(subject, text_content, email_from,None,bcc=recipient_list) #batch 100 ppl to send as bcc
msg.attach_alternative(html_content, "text/html") for i in range(0,len(recipient_list),100):
if attachment_jnf_response: msg = EmailMultiAlternatives(subject, text_content, email_from,None,bcc=recipient_list[i:i+100])
# logger.info(attachment_jnf_response) msg.attach_alternative(html_content, "text/html")
pdf = pdfkit.from_string(attachment_jnf_response['html'], False, if attachment_jnf_response:
options={"--enable-local-file-access": "", '--dpi': '96'}) # logger.info(attachment_jnf_response)
msg.attach(attachment_jnf_response['name'], pdf, 'application/pdf') pdf = pdfkit.from_string(attachment_jnf_response['html'], False,
msg.send() options={"--enable-local-file-access": "", '--dpi': '96'})
msg.attach(attachment_jnf_response['name'], pdf, 'application/pdf')
msg.send()
return True return True
except: except:
logger.error("Send Email: " + str(sys.exc_info())) logger.error("Send Email: " + str(sys.exc_info()))
@ -248,11 +250,15 @@ def PlacementApplicationConditions(student, placement):
return True, "Conditions Satisfied" return True, "Conditions Satisfied"
for i in selected_companies: for i in selected_companies:
if int(i.placement.tier) < int(placement.tier): if int(i.placement.tier) != 1 and int(i.placement.tier) <= int(placement.tier):
return False, "Can't apply for this tier"
elif int(i.placement.tier) == 1 and int(placement.tier) != 1:
return False, "Can't apply for this tier" return False, "Can't apply for this tier"
for i in PPO: for i in PPO:
if int(i.tier) < int(placement.tier): if int(i.tier) != 1 and int(i.tier) <= int(placement.tier):
return False, "Can't apply for this tier"
elif int(i.tier) == 1 and int(placement.tier) != 1:
return False, "Can't apply for this tier" return False, "Can't apply for this tier"
if student.degree != 'bTech' and not placement.rs_eligible: if student.degree != 'bTech' and not placement.rs_eligible:
@ -455,7 +461,7 @@ def send_opening_notifications(opening_id, opening_type=PLACEMENT):
logger.warning('Utils - send_opening_notifications: ' + str(sys.exc_info())) logger.warning('Utils - send_opening_notifications: ' + str(sys.exc_info()))
return False return False
def get_eligible_emails(opening_id, opening_type=PLACEMENT): def get_eligible_emails(opening_id, opening_type=PLACEMENT,send_all=False):
try: try:
# print(opening_id, opening_type) # print(opening_id, opening_type)
if opening_type == PLACEMENT: if opening_type == PLACEMENT:
@ -471,6 +477,10 @@ def get_eligible_emails(opening_id, opening_type=PLACEMENT):
isinstance(opening,Internship) and InternshipApplicationConditions(student, opening)[0]): isinstance(opening,Internship) and InternshipApplicationConditions(student, opening)[0]):
try: try:
student_user = get_object_or_404(User, id=student.id) student_user = get_object_or_404(User, id=student.id)
#if send_all True send all students eligible for the opening
if send_all:
emails.append(student_user.email)
continue
# check if he applied # check if he applied
if opening_type == PLACEMENT: if opening_type == PLACEMENT:
if PlacementApplication.objects.filter(student=student, placement=opening).exists(): if PlacementApplication.objects.filter(student=student, placement=opening).exists():
@ -563,12 +573,13 @@ def send_email_for_opening(opening):
@background_task.background(schedule=2) @background_task.background(schedule=2)
def send_opening_to_notifications_service(id,name,deadline,role): def send_opening_to_notifications_service(id,name,deadline,role,opening_type=PLACEMENT):
data={ data={
"id":id, "id":id,
"company":name, "company":name,
"deadline":deadline, "deadline":deadline,
"role":role "role":role,
"opening_type":opening_type
} }
encoded=jwt.encode(data,os.environ.get("JWT_SECRET_KEY"),algorithm="HS256") encoded=jwt.encode(data,os.environ.get("JWT_SECRET_KEY"),algorithm="HS256")
data_={ data_={

View File

@ -47,7 +47,8 @@ INSTALLED_APPS = [
'background_task', 'background_task',
'simple_history', 'simple_history',
'import_export', 'import_export',
'django_extensions' 'django_extensions',
'django_crontab',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@ -203,3 +204,7 @@ LOGGING = {
} }
# django_heroku.settings(locals()) # django_heroku.settings(locals())
CRONJOBS = [
('0 8,20 * * *', 'APIs.cron.clean_up_tests')
]

View File

@ -1 +1 @@
gunicorn --certfile=/home/cdc/Desktop/1f9476e3959ebe60.crt --keyfile=/home/cdc/Desktop/star_iitdh_key.key --bind localhost:8000 CDC_Backend.wsgi --access-logfile access.log --error-logfile error.log --forwarded-allow-ips="cdc.iitdh.ac.in" & gunicorn --certfile=/home/cdc/Desktop/1f9476e3959ebe60.crt --keyfile=/home/cdc/Desktop/star_iitdh_key.key --bind localhost:8000 CDC_Backend.wsgi --access-logfile access.log --error-logfile error.log --forwarded-allow-ips="cdc.iitdh.ac.in"

View File

@ -13,6 +13,7 @@ Django==3.2.13
django-background-tasks==1.2.5 django-background-tasks==1.2.5
django-compat==1.0.15 django-compat==1.0.15
django-cors-headers==3.11.0 django-cors-headers==3.11.0
django-crontab==0.7.1
django-db-logger==0.1.12 django-db-logger==0.1.12
django-extensions==3.2.1 django-extensions==3.2.1
django-import-export==2.8.0 django-import-export==2.8.0

View File

@ -8,7 +8,7 @@ python3 manage.py migrate
echo "Migrations complete" echo "Migrations complete"
python3 manage.py collectstatic --noinput python3 manage.py collectstatic --noinput
python3 manage.py crontab add
DIR="./Storage" DIR="./Storage"
if [ -d "$DIR" ]; then if [ -d "$DIR" ]; then
### Take action if $DIR exists ### ### Take action if $DIR exists ###