diff --git a/FusionIIIT/Fusion/urls.py b/FusionIIIT/Fusion/urls.py index e3b3f6792..96114032a 100755 --- a/FusionIIIT/Fusion/urls.py +++ b/FusionIIIT/Fusion/urls.py @@ -47,7 +47,7 @@ url(r'^complaint/', include('applications.complaint_system.urls')), url(r'^healthcenter/', include('applications.health_center.urls')), url(r'^leave/', include('applications.leave.urls')), - url(r'^placement/', include('applications.placement_cell.urls')), + url(r'^placement-cell/', include('applications.placement_cell.api.urls')), url(r'^filetracking/', include('applications.filetracking.urls')), url(r'^spacs/', include('applications.scholarships.urls')), url(r'^visitorhostel/', include('applications.visitor_hostel.urls')), diff --git a/FusionIIIT/applications/globals/api/serializers.py b/FusionIIIT/applications/globals/api/serializers.py index d90e0d921..8862b5228 100644 --- a/FusionIIIT/applications/globals/api/serializers.py +++ b/FusionIIIT/applications/globals/api/serializers.py @@ -7,10 +7,6 @@ from applications.globals.models import (ExtraInfo, HoldsDesignation, DepartmentInfo, Designation) -from applications.placement_cell.api.serializers import (SkillSerializer, HasSerializer, - EducationSerializer, CourseSerializer, ExperienceSerializer, - ProjectSerializer, AchievementSerializer, PublicationSerializer, - PatentSerializer, PlacementStatusSerializer, NotifyStudentSerializer) User = get_user_model() diff --git a/FusionIIIT/applications/globals/api/views.py b/FusionIIIT/applications/globals/api/views.py index 7a38063cf..126ca646f 100644 --- a/FusionIIIT/applications/globals/api/views.py +++ b/FusionIIIT/applications/globals/api/views.py @@ -1,8 +1,6 @@ from django.contrib.auth import get_user_model from applications.academic_information.models import Student -from applications.placement_cell.models import (Achievement, Course, Education, - Experience, Has, Patent, - Project, Publication, Skill) + from applications.programme_curriculum.models import ( Course as CurriculumCourse, CourseSlot, CourseInstructor ) @@ -148,42 +146,24 @@ def profile(request, username=None): user = get_object_or_404(User, username=username) if username else request.user profile = serializers.ExtraInfoSerializer(user.extrainfo).data + current = serializers.HoldsDesignationSerializer(user.current_designation.all(), many=True).data if profile['user_type'] == 'student': student = user.extrainfo.student std_sem = student.curr_semester_no - skills = list( - Has.objects.filter(unique_id_id=student) - .select_related("skill_id") - .values("skill_id__skill", "skill_rating") - ) - formatted_skills = [ - {"skill_name": skill["skill_id__skill"], "skill_rating": skill["skill_rating"]} - for skill in skills - ] - education = serializers.EducationSerializer(student.education_set.all(), many=True).data - course = serializers.CourseSerializer(student.course_set.all(), many=True).data - experience = serializers.ExperienceSerializer(student.experience_set.all(), many=True).data - project = serializers.ProjectSerializer(student.project_set.all(), many=True).data - achievement = serializers.AchievementSerializer(student.achievement_set.all(), many=True).data - publication = serializers.PublicationSerializer(student.publication_set.all(), many=True).data - patent = serializers.PatentSerializer(student.patent_set.all(), many=True).data - current = serializers.HoldsDesignationSerializer(user.current_designation.all(), many=True).data resp = { - 'profile' : profile, + 'profile' : profile, 'semester_no' : std_sem, - 'skills' : formatted_skills, - 'education' : education, - 'course' : course, - 'experience' : experience, - 'project' : project, - 'achievement' : achievement, - 'publication' : publication, - 'patent' : patent, - 'current' : current + 'skills' : [], + 'education' : [], + 'course' : [], + 'experience' : [], + 'project' : [], + 'achievement' : [], + 'publication' : [], + 'patent' : [], + 'current' : current, } - return Response(data=resp, status=status.HTTP_200_OK) else: - current = serializers.HoldsDesignationSerializer(user.current_designation.all(), many=True).data resp = { 'profile' : profile, 'semester_no' : None, @@ -197,7 +177,7 @@ def profile(request, username=None): 'patent' : [], 'current' : current, } - return Response(data=resp, status=status.HTTP_200_OK) + return Response(data=resp, status=status.HTTP_200_OK) @api_view(['PUT']) @permission_classes([IsAuthenticated]) @@ -214,82 +194,6 @@ def profile_update(request): return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - # For student-only - current = user.current_designation.filter(designation__name="student") - if not current: - return Response({'error': 'Cannot update'}, status=status.HTTP_400_BAD_REQUEST) - - student = profile.student - if 'education' in request.data: - data = request.data - data['education']['unique_id'] = profile - serializer = serializers.EducationSerializer(data=data['education']) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - elif 'skillsubmit' in request.data: - try: - skill_data = request.data['skillsubmit'] - skill_id = skill_data['skill_id'] - skill_name = skill_id['skill_name'] - skill_rating = skill_data['skill_rating'] - - if not skill_name or skill_rating is None: - return Response({"error": "Missing skill_name or skill_rating"}, status=status.HTTP_400_BAD_REQUEST) - - skill, _ = Skill.objects.get_or_create(skill=skill_name) - has_obj, created = Has.objects.get_or_create(skill_id=skill, unique_id=student, defaults={"skill_rating": skill_rating}) - if not created: - has_obj.skill_rating = skill_rating - has_obj.save(update_fields=['skill_rating']) - - return Response({"message": "Skill added successfully"}, status=status.HTTP_200_OK) - - except Exception as e: - return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) - elif 'achievementsubmit' in request.data: - request.data['achievementsubmit']['unique_id'] = profile - serializer = serializers.AchievementSerializer(data=request.data['achievementsubmit']) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - elif 'publicationsubmit' in request.data: - request.data['publicationsubmit']['unique_id'] = profile - serializer = serializers.PublicationSerializer(data=request.data['publicationsubmit']) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - elif 'patentsubmit' in request.data: - request.data['patentsubmit']['unique_id'] = profile - serializer = serializers.PatentSerializer(data=request.data['patentsubmit']) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - elif 'coursesubmit' in request.data: - request.data['coursesubmit']['unique_id'] = profile - serializer = serializers.CourseSerializer(data=request.data['coursesubmit']) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - elif 'projectsubmit' in request.data: - request.data['projectsubmit']['unique_id'] = profile - serializer = serializers.ProjectSerializer(data=request.data['projectsubmit']) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - elif 'experiencesubmit' in request.data: - request.data['experiencesubmit']['unique_id'] = profile - serializer = serializers.ExperienceSerializer(data=request.data['experiencesubmit']) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'error': 'Cannot update'}, status=status.HTTP_400_BAD_REQUEST) @api_view(['DELETE']) @@ -301,38 +205,6 @@ def profile_delete(request, id): # All records are scoped to the requesting user's own profile via unique_id__extrainfo. # Using get_object_or_404 with the ownership filter ensures that a record belonging # to another user is indistinguishable from a missing record (no ID enumeration). - if 'deleteskill' in request.data: - skill = get_object_or_404(Has, id=id, unique_id__extrainfo=profile) - skill.delete() - return Response({'message': 'Skill deleted successfully'}, status=status.HTTP_200_OK) - elif 'deleteedu' in request.data: - education = get_object_or_404(Education, id=id, unique_id__extrainfo=profile) - education.delete() - return Response({'message': 'Education deleted successfully'}, status=status.HTTP_200_OK) - elif 'deletecourse' in request.data: - course = get_object_or_404(Course, id=id, unique_id__extrainfo=profile) - course.delete() - return Response({'message': 'Course deleted successfully'}, status=status.HTTP_200_OK) - elif 'deleteexp' in request.data: - experience = get_object_or_404(Experience, id=id, unique_id__extrainfo=profile) - experience.delete() - return Response({'message': 'Experience deleted successfully'}, status=status.HTTP_200_OK) - elif 'deletepro' in request.data: - project = get_object_or_404(Project, id=id, unique_id__extrainfo=profile) - project.delete() - return Response({'message': 'Project deleted successfully'}, status=status.HTTP_200_OK) - elif 'deleteach' in request.data: - achievement = get_object_or_404(Achievement, id=id, unique_id__extrainfo=profile) - achievement.delete() - return Response({'message': 'Achievement deleted successfully'}, status=status.HTTP_200_OK) - elif 'deletepub' in request.data: - publication = get_object_or_404(Publication, id=id, unique_id__extrainfo=profile) - publication.delete() - return Response({'message': 'Publication deleted successfully'}, status=status.HTTP_200_OK) - elif 'deletepat' in request.data: - patent = get_object_or_404(Patent, id=id, unique_id__extrainfo=profile) - patent.delete() - return Response({'message': 'Patent deleted successfully'}, status=status.HTTP_200_OK) return Response({'error': 'Wrong attribute'}, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) diff --git a/FusionIIIT/applications/globals/views.py b/FusionIIIT/applications/globals/views.py index 9109d748b..16000ad5a 100644 --- a/FusionIIIT/applications/globals/views.py +++ b/FusionIIIT/applications/globals/views.py @@ -18,14 +18,6 @@ from applications.globals.models import (ExtraInfo, Feedback, HoldsDesignation, Issue, IssueImage, DepartmentInfo,ModuleAccess) from applications.gymkhana.views import coordinator_club -from applications.placement_cell.forms import (AddAchievement, AddCourse, - AddEducation, AddExperience, - AddPatent, AddProfile, - AddProject, AddPublication, - AddSkill) -from applications.placement_cell.models import (Achievement, Course, Education, - Experience, Has, Patent, - Project, Publication, Skill, PlacementStatus) from Fusion.settings.common import LOGIN_URL from notifications.models import Notification from .models import * @@ -902,23 +894,6 @@ def profile(request, username=None): student = get_object_or_404(Student, Q(id=profile.id)) print("student",student) if editable and request.method == 'POST': - if 'studentapprovesubmit' in request.POST: - status = PlacementStatus.objects.select_related('notify_id','unique_id__id__user','unique_id__id__department').filter(pk=request.POST['studentapprovesubmit']).update(invitation='ACCEPTED', timestamp=timezone.now()) - if 'studentdeclinesubmit' in request.POST: - status = PlacementStatus.objects.select_related('notify_id','unique_id__id__user','unique_id__id__department').filter(Q(pk=request.POST['studentdeclinesubmit'])).update(invitation='REJECTED', timestamp=timezone.now()) - if 'educationsubmit' in request.POST: - form = AddEducation(request.POST) - if form.is_valid(): - institute = form.cleaned_data['institute'] - degree = form.cleaned_data['degree'] - grade = form.cleaned_data['grade'] - stream = form.cleaned_data['stream'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - education_obj = Education.objects.create(unique_id=student, degree=degree, - grade=grade, institute=institute, - stream=stream, sdate=sdate, edate=edate) - education_obj.save() if 'profilesubmit' in request.POST: about_me = request.POST.get('about') age = request.POST.get('age') @@ -931,178 +906,11 @@ def profile(request, username=None): extrainfo_obj.phone_no = contact extrainfo_obj.save() profile = get_object_or_404(ExtraInfo, Q(user=user)) - if 'picsubmit' in request.POST: - form = AddProfile(request.POST, request.FILES) - extrainfo_obj = ExtraInfo.objects.select_related('user','department').get(user=user) - extrainfo_obj.profile_picture = form.cleaned_data["pic"] - extrainfo_obj.save() - if 'skillsubmit' in request.POST: - form = AddSkill(request.POST) - if form.is_valid(): - skill = form.cleaned_data['skill'] - skill_rating = form.cleaned_data['skill_rating'] - try: - skill_id = Skill.objects.get(skill=skill) - except Exception as e: - skill_id = Skill.objects.create(skill=skill) - skill_id.save() - has_obj = Has.objects.create(unique_id=student, - skill_id=skill_id, - skill_rating = skill_rating) - has_obj.save() - if 'achievementsubmit' in request.POST: - form = AddAchievement(request.POST) - if form.is_valid(): - achievement = form.cleaned_data['achievement'] - achievement_type = form.cleaned_data['achievement_type'] - description = form.cleaned_data['description'] - issuer = form.cleaned_data['issuer'] - date_earned = form.cleaned_data['date_earned'] - achievement_obj = Achievement.objects.create(unique_id=student, - achievement=achievement, - achievement_type=achievement_type, - description=description, - issuer=issuer, - date_earned=date_earned) - achievement_obj.save() - if 'publicationsubmit' in request.POST: - form = AddPublication(request.POST) - if form.is_valid(): - publication_title = form.cleaned_data['publication_title'] - description = form.cleaned_data['description'] - publisher = form.cleaned_data['publisher'] - publication_date = form.cleaned_data['publication_date'] - publication_obj = Publication.objects.create(unique_id=student, - publication_title= - publication_title, - publisher=publisher, - description=description, - publication_date=publication_date) - publication_obj.save() - if 'patentsubmit' in request.POST: - form = AddPatent(request.POST) - if form.is_valid(): - patent_name = form.cleaned_data['patent_name'] - description = form.cleaned_data['description'] - patent_office = form.cleaned_data['patent_office'] - patent_date = form.cleaned_data['patent_date'] - patent_obj = Patent.objects.create(unique_id=student, patent_name=patent_name, - patent_office=patent_office, - description=description, - patent_date=patent_date) - patent_obj.save() - if 'coursesubmit' in request.POST: - form = AddCourse(request.POST) - if form.is_valid(): - course_name = form.cleaned_data['course_name'] - description = form.cleaned_data['description'] - license_no = form.cleaned_data['license_no'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - course_obj = Course.objects.create(unique_id=student, course_name=course_name, - license_no=license_no, - description=description, - sdate=sdate, edate=edate) - course_obj.save() - if 'projectsubmit' in request.POST: - form = AddProject(request.POST) - if form.is_valid(): - project_name = form.cleaned_data['project_name'] - project_status = form.cleaned_data['project_status'] - summary = form.cleaned_data['summary'] - project_link = form.cleaned_data['project_link'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - project_obj = Project.objects.create(unique_id=student, summary=summary, - project_name=project_name, - project_status=project_status, - project_link=project_link, - sdate=sdate, edate=edate) - project_obj.save() - if 'experiencesubmit' in request.POST: - form = AddExperience(request.POST) - if form.is_valid(): - title = form.cleaned_data['title'] - status = form.cleaned_data['status'] - company = form.cleaned_data['company'] - location = form.cleaned_data['location'] - description = form.cleaned_data['description'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - experience_obj = Experience.objects.create(unique_id=student, title=title, - company=company, location=location, - status=status, - description=description, - sdate=sdate, edate=edate) - experience_obj.save() - if 'deleteskill' in request.POST: - hid = request.POST['deleteskill'] - hs = Has.objects.select_related('skill_id','unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - if 'deleteedu' in request.POST: - hid = request.POST['deleteedu'] - hs = Education.objects.select_related('unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - if 'deletecourse' in request.POST: - hid = request.POST['deletecourse'] - hs = Course.objects.select_related('unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - if 'deleteexp' in request.POST: - hid = request.POST['deleteexp'] - hs = Experience.objects.select_related('unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - if 'deletepro' in request.POST: - hid = request.POST['deletepro'] - hs = Project.objects.select_related('unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - if 'deleteach' in request.POST: - hid = request.POST['deleteach'] - hs = Achievement.objects.select_related('unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - if 'deletepub' in request.POST: - hid = request.POST['deletepub'] - hs = Publication.objects.select_related('unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - if 'deletepat' in request.POST: - hid = request.POST['deletepat'] - hs = Patent.objects.select_related('unique_id__id__user','unique_id__id__department').get(Q(pk=hid)) - hs.delete() - - form = AddEducation(initial={}) - form1 = AddProfile(initial={}) - form10 = AddSkill(initial={}) - form11 = AddCourse(initial={}) - form12 = AddAchievement(initial={}) - form5 = AddPublication(initial={}) - form6 = AddProject(initial={}) - form7 = AddPatent(initial={}) - form8 = AddExperience(initial={}) - form14 = AddProfile() - skills = Has.objects.select_related('skill_id','unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - education = Education.objects.select_related('unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - course = Course.objects.select_related('unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - experience = Experience.objects.select_related('unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - project = Project.objects.select_related('unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - achievement = Achievement.objects.select_related('unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - publication = Publication.objects.select_related('unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - patent = Patent.objects.select_related('unique_id__id__user','unique_id__id__department').filter(Q(unique_id=student)) - context = {'user': user, 'profile': profile, 'skills': skills, - 'educations': education, 'courses': course, 'experiences': experience, - 'projects': project, 'achievements': achievement, 'publications': publication, - 'patent': patent, 'form': form, 'form1': form1, 'form14': form14, - 'form5': form5, 'form6': form6, 'form7': form7, 'form8': form8, - 'form10':form10, 'form11':form11, 'form12':form12, 'current':current, - 'editable': editable - } - if 'skillsubmit' in request.POST or 'deleteskill' in request.POST: - return render(request, "globals/student_profile2.html", context) - if 'coursesubmit' in request.POST or 'educationsubmit' in request.POST or 'deleteedu' in request.POST or 'deletecourse' in request.POST: - return render(request, "globals/student_profile3.html", context) - if 'experiencesubmit' in request.POST or 'projectsubmit' in request.POST or 'deleteexp' in request.POST or 'deletepro' in request.POST: - return render(request, "globals/student_profile4.html", context) - if 'achievementsubmit' in request.POST or 'deleteach' in request.POST: - return render(request, "globals/student_profile5.html", context) - # print("context",context) + + context = {'user': user, 'profile': profile, 'skills': [], + 'educations': [], 'courses': [], 'experiences': [], + 'projects': [], 'achievements': [], 'publications': [], + 'patent': [], 'current': current, 'editable': editable} return render(request, "globals/student_profile.html", context) else: return redirect("/") diff --git a/FusionIIIT/applications/placement_cell/__init__.py b/FusionIIIT/applications/placement_cell/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/FusionIIIT/applications/placement_cell/admin.py b/FusionIIIT/applications/placement_cell/admin.py index e333e2a68..0b1420e40 100644 --- a/FusionIIIT/applications/placement_cell/admin.py +++ b/FusionIIIT/applications/placement_cell/admin.py @@ -1,120 +1,65 @@ from django.contrib import admin -from .models import (Achievement, ChairmanVisit, Coauthor, Coinventor, Course, - Education, Experience, Has, Interest, MessageOfficer, Conference, - NotifyStudent, Patent, PlacementRecord, PlacementSchedule, - PlacementStatus, Project, Publication, Skill, Extracurricular, - StudentPlacement, StudentRecord, Role, CompanyDetails, Reference) +from .models import ( + Company, JobPost, PlacementApplication, PlacementAnnouncement, + PlacementResult, PlacementSchedule, PlacementStatistics, + StudentPlacementProfile, +) -# Register your models here. -class ProjectAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'project_name', 'project_status', 'sdate') +@admin.register(Company) +class CompanyAdmin(admin.ModelAdmin): + list_display = ['name', 'sector', 'website', 'created_at'] + search_fields = ['name', 'sector'] + list_filter = ['sector'] -class SkillAdmin(admin.ModelAdmin): - fields = ['skill'] +@admin.register(JobPost) +class JobPostAdmin(admin.ModelAdmin): + list_display = ['company', 'role', 'job_type', 'ctc', 'deadline', 'is_active'] + list_filter = ['job_type', 'is_active'] + search_fields = ['company__name', 'role'] + raw_id_fields = ['company', 'created_by'] -class HasAdmin(admin.ModelAdmin): - list_display = ('skill_id', 'unique_id') - - -class EducationAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'degree', 'institute', 'stream', 'sdate', 'edate') - - -class ExperienceAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'title', 'status', 'company', 'location', 'sdate', 'edate') - - -class CourseAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'course_name', 'sdate', 'edate') - - -class PublicationAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'publication_title', 'publisher', 'publication_date') - - -class AchievementAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'achievement', 'achievement_type', 'issuer', 'date_earned') - - -class CoauthorAdmin(admin.ModelAdmin): - list_display = ('publication_id', 'coauthor_name') - - -class InterestAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'interest') - - -class PatentAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'patent_name', 'patent_office', 'patent_date') - - -class CoinventorAdmin(admin.ModelAdmin): - list_display = ('patent_id', 'coinventor_name') - - -class StudentPlacementAdmin(admin.ModelAdmin): - list_display = ('unique_id', 'debar', 'future_aspect', 'placed_type', 'placement_date', - 'package') - - -class MessageOfficerAdmin(admin.ModelAdmin): - fields = ['timestamp'] - - -class NotifyStudentAdmin(admin.ModelAdmin): - list_display = ('placement_type', 'company_name', 'ctc') +@admin.register(PlacementSchedule) +class PlacementScheduleAdmin(admin.ModelAdmin): + list_display = ['job_post', 'round_number', 'round_name', 'scheduled_at', 'venue'] + list_filter = ['job_post__company'] + search_fields = ['round_name', 'job_post__company__name'] -class PlacementStatusAdmin(admin.ModelAdmin): - list_display = ('notify_id', 'unique_id', 'placed', 'timestamp') +@admin.register(PlacementApplication) +class PlacementApplicationAdmin(admin.ModelAdmin): + list_display = ['student', 'job_post', 'status', 'applied_at', 'updated_at'] + list_filter = ['status'] + search_fields = ['student__user__username', 'job_post__company__name'] + raw_id_fields = ['student', 'job_post'] -class PlacementRecordAdmin(admin.ModelAdmin): - list_display = ('placement_type', 'name', 'ctc', 'year', 'test_score', 'test_type') +@admin.register(PlacementResult) +class PlacementResultAdmin(admin.ModelAdmin): + list_display = ['application', 'offer_date', 'ctc_offered', 'is_confirmed'] + list_filter = ['is_confirmed'] + raw_id_fields = ['application'] -class StudentRecordAdmin(admin.ModelAdmin): - list_display = ('record_id', 'unique_id') +@admin.register(StudentPlacementProfile) +class StudentPlacementProfileAdmin(admin.ModelAdmin): + list_display = ['student', 'is_placed', 'opted_out', 'updated_at'] + list_filter = ['is_placed', 'opted_out'] + search_fields = ['student__user__username'] + raw_id_fields = ['student'] -class ChairmanVisitAdmin(admin.ModelAdmin): - list_display = ('company_name', 'location', 'visiting_date', 'timestamp') +@admin.register(PlacementAnnouncement) +class PlacementAnnouncementAdmin(admin.ModelAdmin): + list_display = ['title', 'posted_by', 'posted_at', 'is_pinned'] + list_filter = ['is_pinned'] + search_fields = ['title'] -class PlacementScheduleAdmin(admin.ModelAdmin): - list_display = ('title', 'placement_date', 'location', 'time') - - -class ReferenceAdmin(admin.ModelAdmin): - list_display = ('reference_name', 'post', 'email', 'mobile_number') - - -admin.site.register(Project, ProjectAdmin) -admin.site.register(Skill, SkillAdmin) -admin.site.register(Has, HasAdmin) -admin.site.register(Education, EducationAdmin) -admin.site.register(Experience, ExperienceAdmin) -admin.site.register(Course, CourseAdmin) -admin.site.register(Publication, PublicationAdmin) -admin.site.register(Achievement, AchievementAdmin) -admin.site.register(Coauthor, CoauthorAdmin) -admin.site.register(Patent, PatentAdmin) -admin.site.register(Coinventor, CoinventorAdmin) -admin.site.register(Interest, InterestAdmin) -admin.site.register(StudentPlacement, StudentPlacementAdmin) -admin.site.register(MessageOfficer, MessageOfficerAdmin) -admin.site.register(NotifyStudent, NotifyStudentAdmin) -admin.site.register(PlacementStatus, PlacementStatusAdmin) -admin.site.register(PlacementRecord, PlacementRecordAdmin) -admin.site.register(StudentRecord, StudentRecordAdmin) -admin.site.register(ChairmanVisit, ChairmanVisitAdmin) -admin.site.register(PlacementSchedule, PlacementScheduleAdmin) -admin.site.register(Role) -admin.site.register(CompanyDetails) -admin.site.register(Reference) -admin.site.register(Extracurricular) -admin.site.register(Conference) +@admin.register(PlacementStatistics) +class PlacementStatisticsAdmin(admin.ModelAdmin): + list_display = ['batch_year', 'total_students', 'total_placed', 'total_companies', 'avg_ctc', 'updated_at'] + ordering = ['-batch_year'] diff --git a/FusionIIIT/applications/placement_cell/api/__init__.py b/FusionIIIT/applications/placement_cell/api/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/FusionIIIT/applications/placement_cell/api/serializers.py b/FusionIIIT/applications/placement_cell/api/serializers.py index e6960adb0..8f29435f8 100644 --- a/FusionIIIT/applications/placement_cell/api/serializers.py +++ b/FusionIIIT/applications/placement_cell/api/serializers.py @@ -1,84 +1,192 @@ -from rest_framework.authtoken.models import Token from rest_framework import serializers -from applications.placement_cell.models import (Achievement, Course, Education, - Experience, Has, Patent, - Project, Publication, Skill, - PlacementStatus, NotifyStudent) +from applications.placement_cell.models import ( + Company, JobPost, PlacementSchedule, PlacementApplication, + PlacementResult, StudentPlacementProfile, PlacementAnnouncement, + PlacementStatistics, OffCampusPlacement, +) -class SkillSerializer(serializers.ModelSerializer): +class CompanySerializer(serializers.ModelSerializer): class Meta: - model = Skill - fields = ('__all__') + model = Company + fields = ['id', 'name', 'sector', 'website', 'description', 'created_at'] + read_only_fields = ['id', 'created_at'] -class HasSerializer(serializers.ModelSerializer): - skill_id = SkillSerializer() +class PlacementScheduleSerializer(serializers.ModelSerializer): class Meta: - model = Has - fields = ('skill_id','skill_rating') + model = PlacementSchedule + fields = ['id', 'round_number', 'round_name', 'scheduled_at', 'venue', 'notes'] + read_only_fields = ['id'] - def create(self, validated_data): - skill = validated_data.pop('skill_id') - skill_id, created = Skill.objects.get_or_create(**skill) - try: - has_obj = Has.objects.create(skill_id=skill_id,**validated_data) - except: - raise serializers.ValidationError({'skill': 'This skill is already present'}) - return has_obj -class EducationSerializer(serializers.ModelSerializer): +class JobPostListSerializer(serializers.ModelSerializer): + company_name = serializers.CharField(source='company.name', read_only=True) + company_id = serializers.IntegerField(source='company.id', read_only=True) + days_left = serializers.SerializerMethodField() class Meta: - model = Education - fields = ('__all__') + model = JobPost + fields = [ + 'id', 'company_id', 'company_name', 'role', 'job_type', 'ctc', 'stipend', + 'location', 'min_cpi', 'deadline', 'is_active', 'days_left', 'apply_link', + 'eligible_batches', 'eligible_programmes', 'eligible_disciplines', + ] -class CourseSerializer(serializers.ModelSerializer): + def get_days_left(self, obj): + from django.utils import timezone + delta = obj.deadline - timezone.now() + return max(0, delta.days) + + +class JobPostDetailSerializer(serializers.ModelSerializer): + company = CompanySerializer(read_only=True) + schedules = PlacementScheduleSerializer(many=True, read_only=True) + days_left = serializers.SerializerMethodField() + + class Meta: + model = JobPost + fields = [ + 'id', 'company', 'role', 'job_type', 'description', 'ctc', 'stipend', + 'location', 'eligible_batches', 'eligible_programmes', 'eligible_disciplines', + 'min_cpi', 'deadline', 'is_active', 'days_left', 'apply_link', 'schedules', 'created_at', + ] + + def get_days_left(self, obj): + from django.utils import timezone + delta = obj.deadline - timezone.now() + return max(0, delta.days) + + +class JobPostWriteSerializer(serializers.ModelSerializer): + class Meta: + model = JobPost + fields = [ + 'company', 'role', 'job_type', 'description', 'ctc', 'stipend', + 'location', 'eligible_batches', 'eligible_programmes', 'eligible_disciplines', + 'min_cpi', 'deadline', 'is_active', 'apply_link', + ] + + +class ApplicationSerializer(serializers.ModelSerializer): + company_name = serializers.CharField(source='job_post.company.name', read_only=True) + role = serializers.CharField(source='job_post.role', read_only=True) + job_type = serializers.CharField(source='job_post.job_type', read_only=True) + deadline = serializers.DateTimeField(source='job_post.deadline', read_only=True) + + class Meta: + model = PlacementApplication + fields = ['id', 'job_post', 'company_name', 'role', 'job_type', 'deadline', 'status', 'applied_at'] + read_only_fields = ['id', 'applied_at'] + + +class ApplicationAdminSerializer(serializers.ModelSerializer): + roll_no = serializers.CharField(source='student.user.username', read_only=True) + student_name = serializers.SerializerMethodField() + email = serializers.CharField(source='student.user.email', read_only=True) + company_name = serializers.CharField(source='job_post.company.name', read_only=True) + role = serializers.CharField(source='job_post.role', read_only=True) + live_cpi = serializers.SerializerMethodField() class Meta: - model = Course - fields = ('__all__') + model = PlacementApplication + fields = [ + 'id', 'roll_no', 'student_name', 'email', 'live_cpi', + 'company_name', 'role', 'status', 'applied_at', 'updated_at', + ] + + def get_student_name(self, obj): + u = obj.student.user + return f"{u.first_name} {u.last_name}".strip() -class ExperienceSerializer(serializers.ModelSerializer): + def get_live_cpi(self, obj): + from applications.placement_cell.selectors import get_student_published_cpi + cpi = get_student_published_cpi(obj.student) + return str(cpi) if cpi is not None else None + +class StudentProfileSerializer(serializers.ModelSerializer): class Meta: - model = Experience - fields = ('__all__') + model = StudentPlacementProfile + fields = ['resume_url', 'linkedin_url', 'github_url', 'is_placed', 'opted_out', 'updated_at'] + read_only_fields = ['is_placed', 'updated_at'] + -class ProjectSerializer(serializers.ModelSerializer): +class StudentAdminSerializer(serializers.ModelSerializer): + roll_no = serializers.CharField(source='student.user.username', read_only=True) + student_name = serializers.SerializerMethodField() + email = serializers.CharField(source='student.user.email', read_only=True) + live_cpi = serializers.SerializerMethodField() class Meta: - model = Project - fields = ('__all__') + model = StudentPlacementProfile + fields = ['roll_no', 'student_name', 'email', 'live_cpi', 'resume_url', 'is_placed', 'opted_out'] + + def get_student_name(self, obj): + u = obj.student.user + return f"{u.first_name} {u.last_name}".strip() -class AchievementSerializer(serializers.ModelSerializer): + def get_live_cpi(self, obj): + from applications.placement_cell.selectors import get_student_published_cpi + cpi = get_student_published_cpi(obj.student) + return str(cpi) if cpi is not None else None + + +class AnnouncementSerializer(serializers.ModelSerializer): + posted_by_name = serializers.SerializerMethodField() class Meta: - model = Achievement - fields = ('__all__') + model = PlacementAnnouncement + fields = ['id', 'title', 'body', 'posted_by_name', 'posted_at', 'is_pinned'] + read_only_fields = ['id', 'posted_at'] + + def get_posted_by_name(self, obj): + if obj.posted_by: + return f"{obj.posted_by.first_name} {obj.posted_by.last_name}".strip() or obj.posted_by.username + return None -class PublicationSerializer(serializers.ModelSerializer): +class AnnouncementWriteSerializer(serializers.ModelSerializer): class Meta: - model = Publication - fields = ('__all__') + model = PlacementAnnouncement + fields = ['title', 'body', 'is_pinned'] -class PatentSerializer(serializers.ModelSerializer): + +class OffCampusPlacementSerializer(serializers.ModelSerializer): + roll_no = serializers.CharField(source='student.user.username', read_only=True) + student_name = serializers.SerializerMethodField() class Meta: - model = Patent - fields = ('__all__') + model = OffCampusPlacement + fields = [ + 'id', 'roll_no', 'student_name', 'company_name', 'role', + 'offer_type', 'ctc', 'stipend', 'offer_date', 'notes', 'created_at', + ] + read_only_fields = ['id', 'created_at'] + + def get_student_name(self, obj): + u = obj.student.user + return f"{u.first_name} {u.last_name}".strip() -class NotifyStudentSerializer(serializers.ModelSerializer): +class OffCampusPlacementWriteSerializer(serializers.ModelSerializer): class Meta: - model = NotifyStudent - fields = ('__all__') + model = OffCampusPlacement + fields = ['student', 'company_name', 'role', 'offer_type', 'ctc', 'stipend', 'offer_date', 'notes'] + -class PlacementStatusSerializer(serializers.ModelSerializer): - notify_id = NotifyStudentSerializer() +class PlacementStatisticsSerializer(serializers.ModelSerializer): + placement_rate = serializers.SerializerMethodField() class Meta: - model = PlacementStatus - fields = ('notify_id', 'invitation', 'placed', 'timestamp', 'no_of_days') + model = PlacementStatistics + fields = [ + 'batch_year', 'total_students', 'total_placed', 'total_companies', + 'avg_ctc', 'highest_ctc', 'placement_rate', 'updated_at', + ] + + def get_placement_rate(self, obj): + if obj.total_students == 0: + return 0.0 + return round(obj.total_placed / obj.total_students * 100, 1) diff --git a/FusionIIIT/applications/placement_cell/api/urls.py b/FusionIIIT/applications/placement_cell/api/urls.py new file mode 100644 index 000000000..0d966bda9 --- /dev/null +++ b/FusionIIIT/applications/placement_cell/api/urls.py @@ -0,0 +1,45 @@ +from django.conf.urls import url + +from . import views + +urlpatterns = [ + # ── Student ────────────────────────────────────────────────────────────── + url(r'^api/stu/dashboard/$', views.student_dashboard, name='pc-stu-dashboard'), + url(r'^api/stu/jobs/$', views.student_job_list, name='pc-stu-jobs'), + url(r'^api/stu/jobs/(?P\d+)/$', views.student_job_detail, name='pc-stu-job-detail'), + url(r'^api/stu/jobs/(?P\d+)/apply/$', views.student_apply, name='pc-stu-apply'), + url(r'^api/stu/applications/$', views.student_applications, name='pc-stu-applications'), + url(r'^api/stu/applications/(?P\d+)/withdraw/$', views.student_withdraw, name='pc-stu-withdraw'), + url(r'^api/stu/profile/$', views.student_profile, name='pc-stu-profile'), + + # ── Placement Officer ──────────────────────────────────────────────────── + url(r'^api/officer/companies/$', views.officer_companies, name='pc-ofc-companies'), + url(r'^api/officer/companies/(?P\d+)/$', views.officer_company_detail, name='pc-ofc-company-detail'), + url(r'^api/officer/jobs/$', views.officer_jobs, name='pc-ofc-jobs'), + url(r'^api/officer/jobs/(?P\d+)/$', views.officer_job_detail, name='pc-ofc-job-detail'), + url(r'^api/officer/jobs/(?P\d+)/toggle/$', views.officer_job_toggle, name='pc-ofc-job-toggle'), + url(r'^api/officer/jobs/(?P\d+)/applicants/$', views.officer_applicants, name='pc-ofc-applicants'), + url(r'^api/officer/applications/(?P\d+)/status/$', views.officer_app_status, name='pc-ofc-app-status'), + url(r'^api/officer/applications/bulk-status/$', views.officer_bulk_status, name='pc-ofc-bulk-status'), + url(r'^api/officer/batches/$', views.officer_batches, name='pc-ofc-batches'), + url(r'^api/officer/students/$', views.officer_students, name='pc-ofc-students'), + url(r'^api/officer/students/update/$', views.officer_student_update, name='pc-ofc-student-update'), + url(r'^api/officer/export/$', views.officer_export, name='pc-ofc-export'), + url(r'^api/officer/announcements/$', views.officer_announcements, name='pc-ofc-announcements'), + url(r'^api/officer/announcements/(?P\d+)/$', views.officer_announcement_delete, name='pc-ofc-announcement-delete'), + url(r'^api/officer/statistics/$', views.officer_statistics, name='pc-ofc-statistics'), + url(r'^api/officer/statistics/refresh/$', views.officer_statistics_refresh, name='pc-ofc-statistics-refresh'), + url(r'^api/officer/offcampus/$', views.officer_offcampus, name='pc-ofc-offcampus'), + url(r'^api/officer/offcampus/(?P\d+)/$', views.officer_offcampus_detail, name='pc-ofc-offcampus-detail'), + + # ── Placement Chairman ─────────────────────────────────────────────────── + url(r'^api/chairman/statistics/$', views.chairman_statistics, name='pc-chm-statistics'), + url(r'^api/chairman/batches/$', views.chairman_batches, name='pc-chm-batches'), + url(r'^api/chairman/students/$', views.chairman_students, name='pc-chm-students'), + url(r'^api/chairman/export/$', views.chairman_export, name='pc-chm-export'), + + # ── Dean / Faculty ─────────────────────────────────────────────────────── + url(r'^api/dean/batches/$', views.dean_batches, name='pc-dean-batches'), + url(r'^api/dean/statistics/$', views.dean_statistics, name='pc-dean-statistics'), + url(r'^api/dean/announcements/$', views.dean_announcements, name='pc-dean-announcements'), +] diff --git a/FusionIIIT/applications/placement_cell/api/views.py b/FusionIIIT/applications/placement_cell/api/views.py new file mode 100644 index 000000000..4ee0f9d7e --- /dev/null +++ b/FusionIIIT/applications/placement_cell/api/views.py @@ -0,0 +1,781 @@ +import io +from functools import wraps + +from django.http import HttpResponse +from rest_framework import status +from rest_framework.authentication import TokenAuthentication +from rest_framework.decorators import api_view, authentication_classes, permission_classes +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response + +from applications.globals.models import ExtraInfo, HoldsDesignation + +from applications.placement_cell import services, selectors +from applications.placement_cell.api.serializers import ( + AnnouncementSerializer, AnnouncementWriteSerializer, + ApplicationAdminSerializer, ApplicationSerializer, + CompanySerializer, JobPostDetailSerializer, JobPostListSerializer, + JobPostWriteSerializer, OffCampusPlacementSerializer, + OffCampusPlacementWriteSerializer, PlacementScheduleSerializer, + PlacementStatisticsSerializer, StudentAdminSerializer, + StudentProfileSerializer, +) +from applications.placement_cell.models import ( + Company, JobPost, OffCampusPlacement, PlacementApplication, PlacementAnnouncement, + PlacementSchedule, PlacementStatistics, StudentPlacementProfile, +) + + +# ─────────────────────────── helpers ──────────────────────────────────────── + +def role_required(allowed_roles): + allowed_lower = {r.lower() for r in allowed_roles} + + def decorator(view_func): + @wraps(view_func) + def _wrapped(request, *args, **kwargs): + user_roles = set( + HoldsDesignation.objects + .filter(user=request.user) + .values_list('designation__name', flat=True) + ) + user_roles_lower = {r.lower() for r in user_roles} + if not (user_roles_lower & allowed_lower): + return Response( + {'error': 'Permission denied. Required role(s): %s' % allowed_roles}, + status=status.HTTP_403_FORBIDDEN, + ) + return view_func(request, *args, **kwargs) + return _wrapped + return decorator + + +def _get_extra_info(request): + return ExtraInfo.objects.select_related('user').get(user=request.user) + + +def _compute_batch_live_stats(batch_id): + """Compute live placement statistics for a given Batch ID.""" + from django.db.models import Q + from applications.academic_information.models import Student + from applications.programme_curriculum.models import Batch + from applications.placement_cell.models import PlacementResult + + try: + batch = Batch.objects.select_related('discipline').get(pk=batch_id) + except Batch.DoesNotExist: + return None + + # ExtraInfo PKs for all students in this batch + extra_ids = list(Student.objects.filter(batch_id=batch_id).values_list('id', flat=True)) + total_students = len(extra_ids) + + # Total placed (profile flag — set by both on-campus and off-campus service functions) + total_placed = StudentPlacementProfile.objects.filter( + student_id__in=extra_ids, is_placed=True + ).count() + + # On-campus: distinct students with a PLACED application + on_campus_placed = ( + PlacementApplication.objects + .filter(student_id__in=extra_ids, status=PlacementApplication.PLACED) + .values('student_id').distinct().count() + ) + + # Off-campus: distinct students with any OffCampusPlacement entry + off_campus_placed = ( + OffCampusPlacement.objects + .filter(student_id__in=extra_ids) + .values('student_id').distinct().count() + ) + + # Companies: distinct on-campus DB companies + distinct off-campus name strings + on_campus_cos = ( + PlacementApplication.objects + .filter(student_id__in=extra_ids, status=PlacementApplication.PLACED) + .values('job_post__company_id').distinct().count() + ) + off_campus_cos = ( + OffCampusPlacement.objects + .filter(student_id__in=extra_ids) + .values_list('company_name', flat=True).distinct().count() + ) + total_companies = on_campus_cos + off_campus_cos + + # CTC: from PlacementResult (on-campus) + OffCampusPlacement.ctc + placed_app_ids = list( + PlacementApplication.objects + .filter(student_id__in=extra_ids, status=PlacementApplication.PLACED) + .values_list('id', flat=True) + ) + result_ctcs = list( + PlacementResult.objects + .filter(application_id__in=placed_app_ids, ctc_offered__isnull=False) + .values_list('ctc_offered', flat=True) + ) + offcampus_ctcs = list( + OffCampusPlacement.objects + .filter(student_id__in=extra_ids, ctc__isnull=False) + .values_list('ctc', flat=True) + ) + all_ctcs = result_ctcs + offcampus_ctcs + avg_ctc = str(round(sum(all_ctcs) / len(all_ctcs), 2)) if all_ctcs else None + highest_ctc = str(max(all_ctcs)) if all_ctcs else None + + placement_rate = round(total_placed / total_students * 100, 1) if total_students > 0 else 0.0 + + return { + 'batch_id': batch.id, + 'batch_label': str(batch), + 'batch_year': str(batch.year), + 'total_students': total_students, + 'total_placed': total_placed, + 'total_companies': total_companies, + 'avg_ctc': avg_ctc, + 'highest_ctc': highest_ctc, + 'placement_rate': placement_rate, + 'on_campus_placed': on_campus_placed, + 'off_campus_placed': off_campus_placed, + } + + +# ─────────────────────────── Student endpoints ────────────────────────────── + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['student']) +def student_dashboard(request): + extra = _get_extra_info(request) + jobs = selectors.list_active_job_posts(extra)[:10] + apps = selectors.list_applications_for_student(extra)[:10] + anncs = selectors.list_announcements()[:5] + cpi = selectors.get_student_published_cpi(extra) + + return Response({ + 'live_cpi': str(cpi) if cpi is not None else None, + 'jobs': JobPostListSerializer(jobs, many=True).data, + 'applications': ApplicationSerializer(apps, many=True).data, + 'announcements': AnnouncementSerializer(anncs, many=True).data, + }) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['student']) +def student_job_list(request): + extra = _get_extra_info(request) + jobs = selectors.list_active_job_posts(extra) + return Response(JobPostListSerializer(jobs, many=True).data) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['student']) +def student_job_detail(request, job_id): + try: + job = selectors.get_job_post_detail(job_id) + except JobPost.DoesNotExist: + return Response({'error': 'Job post not found.'}, status=status.HTTP_404_NOT_FOUND) + return Response(JobPostDetailSerializer(job).data) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['student']) +def student_apply(request, job_id): + extra = _get_extra_info(request) + try: + app = services.apply_to_job(extra, job_id) + except JobPost.DoesNotExist: + return Response({'error': 'Job post not found.'}, status=status.HTTP_404_NOT_FOUND) + except Exception as e: + return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) + return Response(ApplicationSerializer(app).data, status=status.HTTP_201_CREATED) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['student']) +def student_withdraw(request, app_id): + extra = _get_extra_info(request) + try: + services.withdraw_application(app_id, extra) + except PlacementApplication.DoesNotExist: + return Response({'error': 'Application not found.'}, status=status.HTTP_404_NOT_FOUND) + except Exception as e: + return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) + return Response({'message': 'Application withdrawn.'}) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['student']) +def student_applications(request): + extra = _get_extra_info(request) + apps = selectors.list_applications_for_student(extra) + return Response(ApplicationSerializer(apps, many=True).data) + + +@api_view(['GET', 'PUT']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['student']) +def student_profile(request): + extra = _get_extra_info(request) + profile = selectors.get_student_profile(extra) + cpi = selectors.get_student_published_cpi(extra) + + if request.method == 'GET': + data = StudentProfileSerializer(profile).data + data['live_cpi'] = str(cpi) if cpi is not None else None + return Response(data) + + updated = services.upsert_student_profile(extra, request.data) + data = StudentProfileSerializer(updated).data + data['live_cpi'] = str(cpi) if cpi is not None else None + return Response(data) + + +# ─────────────────────────── Placement Officer endpoints ──────────────────── + +@api_view(['GET', 'POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_companies(request): + if request.method == 'GET': + return Response(CompanySerializer(selectors.list_companies(), many=True).data) + + serializer = CompanySerializer(data=request.data) + if not serializer.is_valid(): + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + company = services.create_company(serializer.validated_data) + return Response(CompanySerializer(company).data, status=status.HTTP_201_CREATED) + + +@api_view(['GET', 'PUT', 'DELETE']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_company_detail(request, company_id): + try: + company = Company.objects.get(pk=company_id) + except Company.DoesNotExist: + return Response({'error': 'Company not found.'}, status=status.HTTP_404_NOT_FOUND) + + if request.method == 'GET': + return Response(CompanySerializer(company).data) + if request.method == 'DELETE': + services.delete_company(company_id) + return Response(status=status.HTTP_204_NO_CONTENT) + + serializer = CompanySerializer(company, data=request.data, partial=True) + if not serializer.is_valid(): + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + updated = services.update_company(company_id, serializer.validated_data) + return Response(CompanySerializer(updated).data) + + +@api_view(['GET', 'POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_jobs(request): + if request.method == 'GET': + return Response(JobPostListSerializer(selectors.list_job_posts_admin(), many=True).data) + + serializer = JobPostWriteSerializer(data=request.data) + if not serializer.is_valid(): + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + job = services.create_job_post(serializer.validated_data, request.user) + return Response(JobPostDetailSerializer(job).data, status=status.HTTP_201_CREATED) + + +@api_view(['GET', 'PUT']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_job_detail(request, job_id): + try: + job = selectors.get_job_post_detail(job_id) + except JobPost.DoesNotExist: + return Response({'error': 'Job post not found.'}, status=status.HTTP_404_NOT_FOUND) + + if request.method == 'GET': + return Response(JobPostDetailSerializer(job).data) + + serializer = JobPostWriteSerializer(job, data=request.data, partial=True) + if not serializer.is_valid(): + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + updated = services.update_job_post(job_id, serializer.validated_data) + return Response(JobPostDetailSerializer(updated).data) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_job_toggle(request, job_id): + try: + job = services.toggle_job_post_active(job_id) + except JobPost.DoesNotExist: + return Response({'error': 'Job post not found.'}, status=status.HTTP_404_NOT_FOUND) + return Response({'id': job.id, 'is_active': job.is_active}) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_applicants(request, job_id): + apps = selectors.list_applications_for_job_post(job_id) + return Response(ApplicationAdminSerializer(apps, many=True).data) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_app_status(request, app_id): + new_status = request.data.get('status') + if not new_status: + return Response({'error': 'status is required.'}, status=status.HTTP_400_BAD_REQUEST) + try: + app = services.update_application_status(app_id, new_status) + except PlacementApplication.DoesNotExist: + return Response({'error': 'Application not found.'}, status=status.HTTP_404_NOT_FOUND) + except Exception as e: + return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) + return Response(ApplicationAdminSerializer(app).data) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_bulk_status(request): + ids = request.data.get('ids', []) + new_status = request.data.get('status') + if not ids or not new_status: + return Response({'error': 'ids and status are required.'}, status=status.HTTP_400_BAD_REQUEST) + try: + count = services.bulk_update_application_status(ids, new_status) + except Exception as e: + return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST) + return Response({'updated': count}) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_batches(request): + """ + Returns all batches that have at least one published ResultAnnouncement. + Used to populate the batch filter dropdown on the Students tab. + """ + from applications.examination.models import ResultAnnouncement + from applications.programme_curriculum.models import Batch + + batch_ids = ( + ResultAnnouncement.objects + .filter(announced=True) + .values_list('batch_id', flat=True) + .distinct() + ) + batches = ( + Batch.objects + .filter(id__in=batch_ids) + .select_related('discipline') + .order_by('-year', 'name') + ) + return Response([ + {'id': b.id, 'label': str(b), 'year': b.year} + for b in batches + ]) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_students(request): + """ + Returns students for a given batch_id whose published final CPI is available. + Requires ?batch_id= query param. Without it returns empty list. + """ + from applications.academic_information.models import Student + from applications.examination.models import ResultAnnouncement + from applications.placement_cell.selectors import get_student_published_cpi + + batch_id = request.query_params.get('batch_id') + if not batch_id: + return Response([]) + + students = Student.objects.filter(batch_id=batch_id).select_related('id__user') + + has_published = ResultAnnouncement.objects.filter(batch_id=batch_id, announced=True).exists() + if not has_published: + return Response([]) + + # Batch-fetch off-campus placements for all students in this batch + extra_pks = [stu.pk for stu in students] + offcampus_map = {} + for ocp in OffCampusPlacement.objects.filter(student_id__in=extra_pks).select_related('student'): + offcampus_map.setdefault(ocp.student_id, []).append(ocp.company_name) + + results = [] + for stu in students: + extra = stu.id # ExtraInfo + cpi = get_student_published_cpi(extra) + if cpi is None: + continue + + try: + profile = StudentPlacementProfile.objects.get(student=extra) + is_placed = profile.is_placed + opted_out = profile.opted_out + resume_url = profile.resume_url + except StudentPlacementProfile.DoesNotExist: + is_placed = False + opted_out = False + resume_url = '' + + off_campus = offcampus_map.get(extra.pk, []) + results.append({ + 'roll_no': extra.user.username, + 'student_name': f"{extra.user.first_name} {extra.user.last_name}".strip(), + 'email': extra.user.email, + 'live_cpi': str(cpi), + 'is_placed': is_placed, + 'opted_out': opted_out, + 'resume_url': resume_url, + 'off_campus': off_campus, + }) + + return Response(results) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_export(request): + try: + import openpyxl + except ImportError: + return Response({'error': 'openpyxl not installed.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + rows = selectors.export_placement_data_rows() + wb = openpyxl.Workbook() + ws = wb.active + ws.title = 'Placement Data' + + headers = ['Roll No', 'Name', 'Email', 'Company', 'Role', 'Job Type', 'Status', 'Applied At'] + ws.append(headers) + for row in rows: + ws.append([row.get(k, '') for k in ['roll_no', 'name', 'email', 'company', 'role', 'job_type', 'status', 'applied_at']]) + + buf = io.BytesIO() + wb.save(buf) + buf.seek(0) + response = HttpResponse( + buf.read(), + content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) + response['Content-Disposition'] = 'attachment; filename="placement_data.xlsx"' + return response + + +@api_view(['GET', 'POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_announcements(request): + if request.method == 'GET': + return Response(AnnouncementSerializer(selectors.list_announcements(), many=True).data) + + serializer = AnnouncementWriteSerializer(data=request.data) + if not serializer.is_valid(): + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + announcement = services.create_announcement(serializer.validated_data, request.user) + return Response(AnnouncementSerializer(announcement).data, status=status.HTTP_201_CREATED) + + +@api_view(['DELETE']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_announcement_delete(request, ann_id): + services.delete_announcement(ann_id) + return Response(status=status.HTTP_204_NO_CONTENT) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_statistics(request): + batch_id = request.query_params.get('batch_id') + if batch_id: + data = _compute_batch_live_stats(batch_id) + if data is None: + return Response({'error': 'Batch not found.'}, status=status.HTTP_404_NOT_FOUND) + return Response(data) + stats = selectors.get_placement_statistics() + return Response(PlacementStatisticsSerializer(stats, many=True).data) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_statistics_refresh(request): + batch_year = request.data.get('batch_year') + if not batch_year: + return Response({'error': 'batch_year is required.'}, status=status.HTTP_400_BAD_REQUEST) + stats = services.refresh_statistics(batch_year) + return Response(PlacementStatisticsSerializer(stats).data) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_student_update(request): + """Manually update a student's placement profile fields (is_placed, opted_out).""" + roll_no = request.data.get('roll_no', '').strip() + if not roll_no: + return Response({'error': 'roll_no is required.'}, status=status.HTTP_400_BAD_REQUEST) + try: + extra = ExtraInfo.objects.get(user__username=roll_no) + except ExtraInfo.DoesNotExist: + return Response({'error': 'Student not found.'}, status=status.HTTP_404_NOT_FOUND) + + profile, _ = StudentPlacementProfile.objects.get_or_create(student=extra) + + if 'is_placed' in request.data: + profile.is_placed = bool(request.data['is_placed']) + # opted_out can only be set to True via API (reverting requires office visit) + if request.data.get('opted_out') is True: + profile.opted_out = True + profile.save() + + return Response({'roll_no': roll_no, 'is_placed': profile.is_placed, 'opted_out': profile.opted_out}) + + +@api_view(['GET', 'POST']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_offcampus(request): + if request.method == 'GET': + placements = OffCampusPlacement.objects.select_related('student__user').all() + return Response(OffCampusPlacementSerializer(placements, many=True).data) + + roll_no = request.data.get('roll_no', '').strip() + if not roll_no: + return Response({'error': 'roll_no is required.'}, status=status.HTTP_400_BAD_REQUEST) + try: + student = ExtraInfo.objects.get(user__username=roll_no) + except ExtraInfo.DoesNotExist: + return Response({'error': f'No student found with roll number {roll_no}.'}, status=status.HTTP_400_BAD_REQUEST) + + payload = {k: v for k, v in request.data.items() if k != 'roll_no'} + payload['student'] = student.pk + serializer = OffCampusPlacementWriteSerializer(data=payload) + if not serializer.is_valid(): + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + placement = services.add_offcampus_placement(serializer.validated_data, request.user) + return Response(OffCampusPlacementSerializer(placement).data, status=status.HTTP_201_CREATED) + + +@api_view(['DELETE']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement officer']) +def officer_offcampus_detail(request, ocp_id): + services.delete_offcampus_placement(ocp_id) + return Response(status=status.HTTP_204_NO_CONTENT) + + +# ─────────────────────────── Placement Chairman endpoints ─────────────────── + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement chairman']) +def chairman_statistics(request): + batch_id = request.query_params.get('batch_id') + if batch_id: + data = _compute_batch_live_stats(batch_id) + if data is None: + return Response({'error': 'Batch not found.'}, status=status.HTTP_404_NOT_FOUND) + return Response(data) + stats = selectors.get_placement_statistics() + return Response(PlacementStatisticsSerializer(stats, many=True).data) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement chairman']) +def chairman_batches(request): + from applications.examination.models import ResultAnnouncement + from applications.programme_curriculum.models import Batch + + batch_ids = ( + ResultAnnouncement.objects + .filter(announced=True) + .values_list('batch_id', flat=True) + .distinct() + ) + batches = ( + Batch.objects + .filter(id__in=batch_ids) + .select_related('discipline') + .order_by('-year', 'name') + ) + return Response([ + {'id': b.id, 'label': str(b), 'year': b.year} + for b in batches + ]) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement chairman']) +def chairman_students(request): + from applications.academic_information.models import Student + from applications.examination.models import ResultAnnouncement + from applications.placement_cell.selectors import get_student_published_cpi + + batch_id = request.query_params.get('batch_id') + if not batch_id: + return Response([]) + + students = Student.objects.filter(batch_id=batch_id).select_related('id__user') + + has_published = ResultAnnouncement.objects.filter(batch_id=batch_id, announced=True).exists() + if not has_published: + return Response([]) + + extra_pks = [stu.pk for stu in students] + offcampus_map = {} + for ocp in OffCampusPlacement.objects.filter(student_id__in=extra_pks): + offcampus_map.setdefault(ocp.student_id, []).append(ocp.company_name) + + results = [] + for stu in students: + extra = stu.id + cpi = get_student_published_cpi(extra) + if cpi is None: + continue + + try: + profile = StudentPlacementProfile.objects.get(student=extra) + is_placed = profile.is_placed + opted_out = profile.opted_out + resume_url = profile.resume_url + except StudentPlacementProfile.DoesNotExist: + is_placed = False + opted_out = False + resume_url = '' + + off_campus = offcampus_map.get(extra.pk, []) + results.append({ + 'roll_no': extra.user.username, + 'student_name': f"{extra.user.first_name} {extra.user.last_name}".strip(), + 'email': extra.user.email, + 'live_cpi': str(cpi), + 'is_placed': is_placed, + 'opted_out': opted_out, + 'resume_url': resume_url, + 'off_campus': off_campus, + }) + + return Response(results) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(['placement chairman']) +def chairman_export(request): + try: + import openpyxl + except ImportError: + return Response({'error': 'openpyxl not installed.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + rows = selectors.export_placement_data_rows() + wb = openpyxl.Workbook() + ws = wb.active + ws.title = 'Placement Data' + + headers = ['Roll No', 'Name', 'Email', 'Company', 'Role', 'Job Type', 'Status', 'Applied At'] + ws.append(headers) + for row in rows: + ws.append([row.get(k, '') for k in ['roll_no', 'name', 'email', 'company', 'role', 'job_type', 'status', 'applied_at']]) + + buf = io.BytesIO() + wb.save(buf) + buf.seek(0) + response = HttpResponse( + buf.read(), + content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) + response['Content-Disposition'] = 'attachment; filename="placement_data_full.xlsx"' + return response + + +# ─────────────────────────── Dean / Faculty endpoints ─────────────────────── + +DEAN_ROLES = ['Dean Academic', 'dean', 'Associate Professor', 'Professor', 'Assistant Professor'] + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(DEAN_ROLES) +def dean_batches(request): + from applications.examination.models import ResultAnnouncement + from applications.programme_curriculum.models import Batch + + batch_ids = ( + ResultAnnouncement.objects + .filter(announced=True) + .values_list('batch_id', flat=True) + .distinct() + ) + batches = Batch.objects.filter(id__in=batch_ids).select_related('discipline').order_by('-year', 'name') + return Response([{'id': b.id, 'label': str(b), 'year': b.year} for b in batches]) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(DEAN_ROLES) +def dean_statistics(request): + batch_id = request.query_params.get('batch_id') + if batch_id: + data = _compute_batch_live_stats(batch_id) + if data is None: + return Response({'error': 'Batch not found.'}, status=status.HTTP_404_NOT_FOUND) + return Response(data) + stats = selectors.get_placement_statistics() + return Response(PlacementStatisticsSerializer(stats, many=True).data) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +@authentication_classes([TokenAuthentication]) +@role_required(DEAN_ROLES) +def dean_announcements(request): + return Response(AnnouncementSerializer(selectors.list_announcements(), many=True).data) diff --git a/FusionIIIT/applications/placement_cell/apps.py b/FusionIIIT/applications/placement_cell/apps.py index ad9e331df..048347efc 100644 --- a/FusionIIIT/applications/placement_cell/apps.py +++ b/FusionIIIT/applications/placement_cell/apps.py @@ -1,5 +1,6 @@ -from django.apps import AppConfig - - -class PlacementCellConfig(AppConfig): - name = 'applications.placement_cell' +from django.apps import AppConfig + + +class PlacementCellConfig(AppConfig): + name = 'applications.placement_cell' + verbose_name = 'Placement Cell' diff --git a/FusionIIIT/applications/placement_cell/forms.py b/FusionIIIT/applications/placement_cell/forms.py deleted file mode 100644 index aea81b795..000000000 --- a/FusionIIIT/applications/placement_cell/forms.py +++ /dev/null @@ -1,729 +0,0 @@ - -from datetime import * -from django import forms -from django.core.validators import MaxValueValidator, MinValueValidator - -from applications.academic_information.models import Constants as Con -from applications.globals.models import DepartmentInfo -from django.forms import CheckboxSelectMultiple, MultiWidget, Select - -from .models import Constants, NotifyStudent, Skill, Role - -class AddProfile(forms.ModelForm): - """ - The form is used to change profile picture of user. - @variables: - pic - chosen picture - """ - pic = forms.ImageField() - -class AddEducation(forms.Form): - """ - The form is used to add education detail of user. - @variables: - institute - name of institute of previous education - degree - name of previous degree - grade - obtained grade - stream - chosen stream for respective education - sdate - start date of respective education - edate - end date of respective education - """ - institute = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'field'}), - label="institute") - degree = forms.CharField(widget=forms.TextInput(attrs={'max_length': 40, - 'class': 'field'}), - label="degree") - grade = forms.CharField(widget=forms.TextInput(attrs={'max_length': 10, - 'class': 'form-control'}), - label="grade") - stream = forms.CharField(widget=forms.TextInput(attrs={'max_length': 150, - 'class': 'form-control'}), - label="stream", required=False) - sdate = forms.DateField(label='sdate', widget=forms.DateInput(attrs={'class':'datepicker'})) - edate = forms.DateField(label='edate', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean(self): - sdate = self.cleaned_data.get("sdate") - edate = self.cleaned_data.get("edate") - grade = self.cleaned_data.get("grade") - if (sdate> edate): - raise forms.ValidationError("Start Date but me before End Date") - - if (len(grade)>3): - raise forms.ValidationError("Invalid") - return self.cleaned_data - - -class AddSkill(forms.Form): - """ - The form is used to skills in profile of user. - @variables: - skill - name of the skill user knows - skill_rating - weightage of the skill he knows - """ - skill = forms.CharField(widget=forms.TextInput(attrs={'max_length': 30, - 'class': 'field'}), - label="skill") - skill_rating = forms.IntegerField(widget=forms.NumberInput(attrs={'min':0, 'max':100}), label="skill_rating") - - -class AddCourse(forms.Form): - """ - The form is used to add external courses that user has done. - @variables: - course_name - name of the course - description - description of the course - license_no - licence number of the course - sdate - start date of the course - edate - end date of the course - """ - course_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="course_name") - description = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'field'}), - label="description", required=False) - license_no = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'field'}), - label="license_no", required=False) - sdate = forms.DateField(label='sdate', widget=forms.DateInput(attrs={'class':'datepicker'})) - edate = forms.DateField(label='edate', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean(self): - sdate = self.cleaned_data.get("sdate") - edate = self.cleaned_data.get("edate") - - if (sdate > edate): - raise forms.ValidationError("Start Date but me before End Date") - return self.cleaned_data - - -class AddConference(forms.Form): - """ - The form is used to add external courses that user has done. - @variables: - course_name - name of the course - description - description of the course - license_no - licence number of the course - sdate - start date of the course - edate - end date of the course - """ - conference_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="course_name") - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="description", required=False) - sdate = forms.DateField(label='sdate', widget=forms.DateInput(attrs={'class':'datepicker'})) - edate = forms.DateField(label='edate', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean(self): - sdate = self.cleaned_data.get("sdate") - edate = self.cleaned_data.get("edate") - - if (sdate > edate): - raise forms.ValidationError("Start Date cant be after End Date") - return self.cleaned_data - - -class AddExperience(forms.Form): - """ - The form is used to add experience that useris having. - @variables: - title - title of the experience - status - status of experience (ongoing/ended) - description - description of the experience - company - name of company where experience is gained - location - location of the company - sdate - start date of the company experience - edate - end date of the company experience - """ - title = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="title") - status = forms.ChoiceField(choices = Constants.RESUME_TYPE, label="status", - widget=forms.Select(attrs={'style': "height:45px"})) - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 500, - 'class': 'form-control'}), - label="description", required=False) - company = forms.CharField(widget=forms.TextInput(attrs={'max_length': 200, - 'class': 'form-control'}), - label="company") - location = forms.CharField(widget=forms.TextInput(attrs={'max_length': 200, - 'class': 'form-control'}), - label="location") - sdate = forms.DateField(label='sdate', widget=forms.DateInput(attrs={'class':'datepicker'})) - edate = forms.DateField(label='edate', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean(self): - sdate = self.cleaned_data.get("sdate") - edate = self.cleaned_data.get("edate") - - if (sdate > edate): - raise forms.ValidationError("Start Date cant be after End Date") - return self.cleaned_data - - -class AddProject(forms.Form): - """ - The form is used to add project that user has done. - @variables: - project_name - name of the project - project_status - status of the project (ongoing/ended) - summary - summary of the project - project_link - link of the project - sdate - start date of the project - edate - end date of the project - """ - project_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 50, - 'class': 'field'}), - label="title") - project_status = forms.ChoiceField(choices = Constants.RESUME_TYPE, label="project_status", - widget=forms.Select()) - summary = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="summary", required=False) - project_link = forms.CharField(widget=forms.TextInput(attrs={'max_length': 200, - 'class': 'form-control'}), - label="project_link", required=False) - sdate = forms.DateField(label='sdate', widget=forms.DateInput(attrs={'class':'datepicker'})) - edate = forms.DateField(label='edate', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean(self): - sdate = self.cleaned_data.get("sdate") - edate = self.cleaned_data.get("edate") - - if (sdate > edate): - raise forms.ValidationError("Start Date cant be after End Date") - return self.cleaned_data - - -class AddAchievement(forms.Form): - """ - The form is used to achievement that user has gained. - @variables: - achievement - name of the achievement - achievement_type - type of achievement (educational/others) - description - description of achievement - issuer - issuer of achievement - date_earned - date of earning of achievement - """ - achievement = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="achievement") - achievement_type = forms.ChoiceField(choices = Constants.ACHIEVEMENT_TYPE, - label="achievement_type", widget=forms.Select(attrs={'style': "height:45px"})) - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="description", required=False) - issuer = forms.CharField(widget=forms.TextInput(attrs={'max_length': 200, - 'class': 'form-control'}), - label="issuer") - date_earned = forms.DateField(label='date_earned', widget=forms.DateInput(attrs={'class':'datepicker'})) - - -class AddExtracurricular(forms.Form): - """ - The form is used to add social activity that user has participated. - @variables: - event_name - name of the event - description - description of achievement - name_of_position - name of holding position - date_earned - date of earning of achievement - """ - event_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="event_name") - event_type = forms.ChoiceField(choices = Constants.EVENT_TYPE, - label="event_type", widget=forms.Select(attrs={'style': "height:45px"})) - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="description", required=False) - name_of_position = forms.CharField(widget=forms.TextInput(attrs={'max_length': 200, - 'class': 'form-control'}), - label="name_of_position") - date_earned = forms.DateField(label='date_earned', widget=forms.DateInput(attrs={'class':'datepicker'})) - - - -class AddPublication(forms.Form): - """ - The form is used to add publications that user has published. - @variables: - publication_title - title of publication - description - description of publication - publisher - name of publisher - publication_date - date of publication - """ - publication_title = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="publication_title") - description = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'form-control'}), - label="description", required=False) - publisher = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'form-control'}), - label="publisher") - publication_date = forms.DateField(label='publication_date', widget=forms.DateInput(attrs={'class':'datepicker'})) - - -class AddReference(forms.Form): - """ - The form is used to add reference. - @variables: - reference_name - name of the referenced person - post - post of the referenced person - email - email of the referenced person - mobile_number - mobile number/phone number of the referenced person - """ - reference_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'reference_name'}), - label="reference_name") - post = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'form-control', - 'id': 'reference_post'}), - label="post", required=False) - email = forms.CharField(widget=forms.TextInput(attrs={'max_length': 50, - 'class': 'form-control', - 'id': 'reference_email', - }), - label="email") - mobile_number = forms.CharField(widget=forms.TextInput(attrs={'max_length': 10, - 'class': 'field', - 'id': 'reference_mobile', - 'type': 'number'}), - label="mobile_number") - def clean(self): - mobile_number = self.cleaned_data.get("mobile_number") - if(len(mobile_number)>10): - raise forms.ValidationError("Invalid Number") - return self.cleaned_data - - -class AddPatent(forms.Form): - """ - The form is used to add patents that user has done. - @variables: - patent_name - name of the patent - description - description of the patent - patent_office - office from which patent has been done - patent_date - date of patent - """ - patent_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="patent_name") - description = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'form-control'}), - label="description", required=False) - patent_office = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'form-control'}), - label="patent_office") - patent_date = forms.DateField(label='patent_date', widget=forms.DateInput(attrs={'class':'datepicker'})) - - -class AddProfile(forms.Form): - """ - The form is used to change profile section of user. - @variables: - about_me - about me about the user - age - age of user - address - address of user - """ - about_me = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'field'}), - label="about_me", required=False) - age = forms.IntegerField(widget=forms.NumberInput(attrs={'min': 0}), label="age") - address = forms.CharField(widget=forms.TextInput(attrs={'max_length': 250, - 'class': 'form-control'}), - label="address") - - -class AddChairmanVisit(forms.Form): - """ - The form is used to chairman visit schedule of user. - @variables: - company_name - name of company - location - location of company - description - description of company - visiting_date - date of visiting - """ - company_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="company_name") - location = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="location") - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="description") - visiting_date = forms.DateField(label='visiting_date', widget=forms.DateInput(attrs={'class':'datepicker'})) - - -class SearchStudentRecord(forms.Form): - """ - The form is used to search from the student record based of various parameters. - @variables: - name - name of the student - rollno - roll no of student - programme - programme of student - department - department of student - cpi - cpi of student - skill - skill of student - debar - debarred or not debarred - placed_type - type of placement - """ - name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, 'class': 'field'}), - label="name", required=False) - rollno = forms.IntegerField(label="rollno", widget=forms.NumberInput(attrs={'min': 0}), required=False) - programme = forms.ChoiceField(choices = Con.PROGRAMME, required=False, - label="programme", widget=forms.Select(attrs={'style': "height:45px", - 'onchange': "changeDeptForSearch()", - 'id': "id_programme_search"})) - - dep_btech = forms.MultipleChoiceField(choices = Constants.BTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_bdes = forms.MultipleChoiceField(choices = Constants.BDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mtech = forms.MultipleChoiceField(choices = Constants.MTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mdes = forms.MultipleChoiceField(choices = Constants.MDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_phd = forms.MultipleChoiceField(choices = Constants.PHD_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - - cpi = forms.DecimalField(label="cpi", required=False) - skill = forms.ModelMultipleChoiceField(required=False, widget=forms.SelectMultiple(), - queryset=Skill.objects.all(), label="skill") - debar = forms.ChoiceField(widget=forms.Select(attrs={'style': "height:45px"}), label="debar", required=False, - choices=Constants.DEBAR_TYPE) - placed_type = forms.ChoiceField(widget=forms.Select(attrs={'style': "height:45px"}), label="placed_type", required=False, - choices=Constants.PLACED_TYPE) - # new_field = DepartmentWidget(attrs={}) - - -class SendInvite(forms.Form): - """ - The form is used to send invite to students about upcoming placement or pbi events. - @variables: - company - name of company - """ - company = forms.ModelChoiceField(required=True, queryset=NotifyStudent.objects.all(), label="company") - rollno = forms.CharField(label="rollno", widget=forms.TextInput(attrs={'min': 0}), required=False) - programme = forms.ChoiceField(choices = Con.PROGRAMME, required=False, - label="programme", widget=forms.Select(attrs={'style': "height:45px", - 'onchange': "changeDeptForSend()", - 'id': "id_programme_send"})) - - dep_btech = forms.MultipleChoiceField(choices = Constants.BTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_bdes = forms.MultipleChoiceField(choices = Constants.BDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mtech = forms.MultipleChoiceField(choices = Constants.MTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mdes = forms.MultipleChoiceField(choices = Constants.MDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_phd = forms.MultipleChoiceField(choices = Constants.PHD_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - cpi = forms.DecimalField(label="cpi", required=False) - no_of_days = forms.CharField(required=True, widget=forms.NumberInput(attrs={ 'min':0, - 'max':30, - 'max_length': 10, - 'class': 'form-control'})) - - - -class AddSchedule(forms.Form): - """ - The form is used to placement or pbi schedule. - @variables: - time - time of placement activity - ctc - salary - company_name - name of company - placement_type - placement type (placement/pbi) - location - location of company - description - description of company - placement_date - date of placement activity - """ - time = forms.TimeField(label='time', widget=forms.widgets.TimeInput(attrs={'type': "time", - 'value':"00:00", - 'min':"0:00", - 'max':"24:00"})) - ctc = forms.DecimalField(label="ctc", widget=forms.NumberInput(attrs={ 'min':0, 'step': 0.25}) ) - company_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'list': 'company_dropdown1', - 'id': 'company_input'}), - label="company_name") - placement_type = forms.ChoiceField(widget=forms.Select(attrs={'style': "height:45px"}), label="placement_type", - choices=Constants.PLACEMENT_TYPE) - location = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="location") - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="description", required=False) - attached_file = forms.FileField(required=False) - placement_date = forms.DateField(label='placement_date', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean_ctc(self): - ctc = self.cleaned_data['ctc'] - # print('form validation \n\n\n\n', ctc) - if ctc <= 0: - raise forms.ValidationError("CTC must be positive value") - - return ctc - - def clean_company_name(self): - company_name = self.cleaned_data['company_name'] - # print('form validation \n\n\n\n', ctc) - if NotifyStudent.objects.filter(company_name=company_name): - raise forms.ValidationError("company_name must be unique") - - return company_name - - -def current_year(): - return date.today().year - -def max_value_current_year(value): - return MaxValueValidator(current_year())(value) - -def year_choices(): - return [(r,r) for r in range(1984, date.today().year+1)] -class SearchPlacementRecord(forms.Form): - """ - The form is used to search from placement records based of various parameters. - @variables: - stuname - name of the student - year - year of placement - ctc - salary - roll - roll no of student - cname - name of company - """ - stuname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'add_placement_stuname'}), - label="stuname", required=False) - year = forms.TypedChoiceField(coerce=int, choices=year_choices, initial=current_year, label="year", required=False, widget=forms.NumberInput(attrs={'id': 'add_placement_year'})) - ctc = forms.CharField(label="ctc", required=False, widget=forms.NumberInput(attrs={ 'min':0, 'id': 'add_placement_ctc', 'step': 0.25})) - roll = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, - 'max_length': 10, - 'class': 'form-control', - 'id': 'add_placement_roll'}), - label="roll", required=False) - cname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'add_placement_cname'}), - label="cname", required=False) - - -class SearchPbiRecord(forms.Form): - """ - The form is used to search from pbi record. - @variables: - stuname - name of student - year - year of pbi - ctc - stipend - roll - roll no of student - cname - name of company - """ - stuname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'add_pbi_stuname'}), - label="stuname", required=False) - year = forms.TypedChoiceField(coerce=int, choices=year_choices, initial=current_year, label="year", required=False, widget=forms.NumberInput(attrs={'id': 'add_pbi_year'})) - ctc = forms.DecimalField(label="ctc", required=False, widget=forms.NumberInput(attrs={ 'min':0, 'id': 'add_pbi_ctc', 'step': 0.25})) - roll = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, - 'max_length': 10, - 'class': 'form-control', - 'id': 'add_pbi_roll'}), - label="roll", required=False) - cname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'add_pbi_cname'}), - label="cname", required=False) - - - -class SendInvitation(forms.Form): - """ - The form is used to send invite to students about upcoming placement or pbi events. - @variables: - company - name of company - """ - company = forms.ModelChoiceField(required=True, queryset=NotifyStudent.objects.all(), label="company") - rollno = forms.IntegerField(label="rollno", widget=forms.NumberInput(attrs={'min': 0}), required=False) - programme = forms.ChoiceField(choices = Con.PROGRAMME, required=False, - label="programme", widget=forms.Select(attrs={'style': "height:45px", - 'onchange': "changeDeptForSend()", - 'id': "id_programme_send"})) - - dep_btech = forms.MultipleChoiceField(choices = Constants.BTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_bdes = forms.MultipleChoiceField(choices = Constants.BDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mtech = forms.MultipleChoiceField(choices = Constants.MTECH_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_mdes = forms.MultipleChoiceField(choices = Constants.MDES_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - dep_phd = forms.MultipleChoiceField(choices = Constants.PHD_DEP, required=False, label="department", - widget=forms.CheckboxSelectMultiple) - cpi = forms.DecimalField(label="cpi", required=False) - no_of_days = forms.CharField(required=True, widget=forms.NumberInput(attrs={ 'min':0, - 'max':30, - 'max_length': 10, - 'class': 'form-control'})) - - -class AddPlacementSchedule(forms.Form): - """ - The form is used to placement or pbi schedule. - @variables: - time - time of placement activity - ctc - salary - company_name - name of company - placement_type - placement type (placement/pbi) - location - location of company - description - description of company - placement_date - date of placement activity - """ - time = forms.TimeField(label='time', widget=forms.widgets.TimeInput(attrs={'type': "time", - 'value':"00:00", - 'min':"0:00", - 'max':"24:00"})) - ctc = forms.DecimalField(label="ctc", widget=forms.NumberInput(attrs={ 'min':0, 'step': 0.25}) ) - company_name = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'list': 'company_dropdown1', - 'id': 'company_input'}), - label="company_name") - placement_type = forms.ChoiceField(widget=forms.Select(attrs={'style': "height:45px"}), label="placement_type", - choices=Constants.PLACEMENT_TYPE) - location = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="location") - description = forms.CharField(widget=forms.Textarea(attrs={'max_length': 1000, - 'class': 'form-control'}), - label="description", required=False) - attached_file = forms.FileField(required=False) - placement_date = forms.DateField(label='placement_date', widget=forms.DateInput(attrs={'class':'datepicker'})) - - def clean_ctc(self): - ctc = self.cleaned_data['ctc'] - # print('form validation \n\n\n\n', ctc) - if ctc <= 0: - raise forms.ValidationError("CTC must be positive value") - - return ctc - - def clean_company_name(self): - company_name = self.cleaned_data['company_name'] - # print('form validation \n\n\n\n', ctc) - if NotifyStudent.objects.filter(company_name=company_name): - raise forms.ValidationError("company_name must be unique") - - return company_name - - -class SearchHigherRecord(forms.Form): - """ - The form is used to search from higher study record based on various parameters . - @variables: - roll - roll no of the student - stuname - name of the student - test_type - type of test for higher study - test_score - score in the test - year -year of clearing the test - uname - name of the university - """ - roll = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, 'max_length': 10, - 'class': 'form-control', - 'id': 'add_higher_roll'}), - label="roll", required=False) - stuname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'add_higher_stuname'}), - label="stuname", required=False, - help_text="Only for searching records") - test_type = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'add_higher_test_type'}), - label="test_type", required=False) - test_score = forms.IntegerField(label="test_score", required=False, widget=forms.NumberInput(attrs={'id': 'add_higher_test_score'})) - year = forms.TypedChoiceField(coerce=int, choices=year_choices, initial=current_year, label="year", required=False, widget=forms.NumberInput(attrs={'id': 'add_higher_year'})) - uname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field', - 'id': 'add_higher_uname'}), - label="uname", required=False) - - -class ManagePlacementRecord(forms.Form): - """ - The form is used to manage placement records in the database by searching based on given parameters. - @variables: - stuname - name of the student - roll - roll no of student - company - company name - ctc - salary - """ - stuname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="stuname", required=False) - roll = forms.CharField(widget=forms.TextInput(attrs={ 'min':0, - 'max_length': 10, - 'class': 'form-control'}), - label="roll", required=False) - company = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="company", required=False) - ctc = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, 'step': 0.25}), label="ctc", required=False) - - -class ManagePbiRecord(forms.Form): - """ - The form is used to manage pbi records in the database by searching based on given parameters. - @variables: - stuname - name of student - roll - roll no of student - company - company name - ctc - stipent that company is giving - """ - stuname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="stuname", required=False) - roll = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, - 'max_length': 10, - 'class': 'form-control'}), - label="roll", required=False) - company = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="company", required=False) - ctc = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, 'step': 0.25}), label="ctc", required=False) - - -class ManageHigherRecord(forms.Form): - """ - The form is used to manage Higher Study records in the database by searching based on given parameters. - @variables: - stuname - name of student - roll - roll no of student - test_type - type of test - company - name of university - test_score - score in the test - """ - stuname = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="stuname", required=False) - roll = forms.IntegerField(widget=forms.NumberInput(attrs={ 'min':0, - 'max_length': 10, - 'class': 'form-control'}), - label="roll", required=False) - test_type = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="test_type", required=False) - company = forms.CharField(widget=forms.TextInput(attrs={'max_length': 100, - 'class': 'field'}), - label="company", required=False) - test_score = forms.IntegerField(label="test_score", required=False) diff --git a/FusionIIIT/applications/placement_cell/migrations/0001_initial.py b/FusionIIIT/applications/placement_cell/migrations/0001_initial.py index 712c60a56..044e14d3d 100644 --- a/FusionIIIT/applications/placement_cell/migrations/0001_initial.py +++ b/FusionIIIT/applications/placement_cell/migrations/0001_initial.py @@ -1,9 +1,8 @@ -# Generated by Django 3.1.5 on 2024-07-16 15:44 +# Generated by Django 3.1.5 on 2026-04-30 00:12 -import datetime +from django.conf import settings from django.db import migrations, models import django.db.models.deletion -import django.utils.timezone class Migration(migrations.Migration): @@ -11,279 +10,134 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('academic_information', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('globals', '0006_auto_20260304_0836'), ] operations = [ migrations.CreateModel( - name='ChairmanVisit', + name='Company', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('company_name', models.CharField(default='', max_length=100)), - ('location', models.CharField(default='', max_length=100)), - ('visiting_date', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('description', models.TextField(blank=True, default='', max_length=1000, null=True)), - ('timestamp', models.DateTimeField(auto_now=True)), - ], - ), - migrations.CreateModel( - name='CompanyDetails', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('company_name', models.CharField(blank=True, max_length=100, null=True)), - ], - ), - migrations.CreateModel( - name='MessageOfficer', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('message', models.CharField(default='', max_length=100)), - ('timestamp', models.DateTimeField(auto_now=True)), - ], - ), - migrations.CreateModel( - name='NotifyStudent', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('placement_type', models.CharField(choices=[('PLACEMENT', 'Placement'), ('PBI', 'PBI'), ('HIGHER STUDIES', 'Higher Studies'), ('OTHER', 'Other')], default='PLACEMENT', max_length=20)), - ('company_name', models.CharField(default='', max_length=100)), - ('ctc', models.DecimalField(decimal_places=4, max_digits=10)), - ('description', models.TextField(blank=True, default='', max_length=1000, null=True)), - ('timestamp', models.DateTimeField(auto_now=True)), - ], - ), - migrations.CreateModel( - name='PlacementRecord', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('placement_type', models.CharField(choices=[('PLACEMENT', 'Placement'), ('PBI', 'PBI'), ('HIGHER STUDIES', 'Higher Studies'), ('OTHER', 'Other')], default='PLACEMENT', max_length=20)), - ('name', models.CharField(default='', max_length=100)), - ('ctc', models.DecimalField(decimal_places=2, default=0, max_digits=5)), - ('year', models.IntegerField(default=0)), - ('test_score', models.IntegerField(blank=True, default=0, null=True)), - ('test_type', models.CharField(blank=True, default='', max_length=30, null=True)), - ], - ), - migrations.CreateModel( - name='Role', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('role', models.CharField(blank=True, max_length=100, null=True)), + ('name', models.CharField(max_length=255, unique=True)), + ('sector', models.CharField(max_length=100)), + ('website', models.URLField(blank=True)), + ('description', models.TextField(blank=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), ], + options={ + 'verbose_name_plural': 'Companies', + 'ordering': ['name'], + }, ), migrations.CreateModel( - name='Skill', + name='JobPost', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('skill', models.CharField(default='', max_length=30)), - ], - ), - migrations.CreateModel( - name='StudentPlacement', - fields=[ - ('unique_id', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='academic_information.student')), - ('debar', models.CharField(choices=[('NOT DEBAR', 'Not Debar'), ('DEBAR', 'Debar')], default='NOT DEBAR', max_length=20)), - ('future_aspect', models.CharField(choices=[('PLACEMENT', 'Placement'), ('PBI', 'PBI'), ('HIGHER STUDIES', 'Higher Studies'), ('OTHER', 'Other')], default='PLACEMENT', max_length=20)), - ('placed_type', models.CharField(choices=[('NOT PLACED', 'Not Placed'), ('PLACED', 'Placed')], default='NOT PLACED', max_length=20)), - ('placement_date', models.DateField(blank=True, default=datetime.date.today, null=True, verbose_name='Date')), - ('package', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)), + ('role', models.CharField(max_length=200)), + ('job_type', models.CharField(choices=[('placement', 'Placement'), ('internship', 'Internship')], default='placement', max_length=20)), + ('description', models.TextField(blank=True)), + ('ctc', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)), + ('stipend', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)), + ('location', models.CharField(blank=True, max_length=200)), + ('eligible_batches', models.JSONField(default=list)), + ('eligible_programmes', models.JSONField(default=list)), + ('eligible_disciplines', models.JSONField(default=list)), + ('min_cpi', models.DecimalField(decimal_places=2, default=0.0, max_digits=4)), + ('deadline', models.DateTimeField()), + ('is_active', models.BooleanField(default=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='job_posts', to='placement_cell.company')), + ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_job_posts', to=settings.AUTH_USER_MODEL)), ], + options={ + 'ordering': ['-created_at'], + }, ), migrations.CreateModel( - name='Reference', + name='PlacementApplication', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('reference_name', models.CharField(default='', max_length=100)), - ('post', models.CharField(blank=True, default='', max_length=100, null=True)), - ('email', models.CharField(default='', max_length=50)), - ('mobile_number', models.CharField(blank=True, max_length=15, null=True)), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), + ('status', models.CharField(choices=[('applied', 'Applied'), ('shortlisted', 'Shortlisted'), ('rejected', 'Rejected'), ('placed', 'Placed'), ('withdrawn', 'Withdrawn')], default='applied', max_length=20)), + ('applied_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('job_post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='applications', to='placement_cell.jobpost')), + ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='placement_applications', to='globals.extrainfo')), ], + options={ + 'ordering': ['-applied_at'], + 'unique_together': {('job_post', 'student')}, + }, ), migrations.CreateModel( - name='Publication', + name='PlacementStatistics', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('publication_title', models.CharField(default='', max_length=100)), - ('description', models.TextField(blank=True, default='', max_length=250, null=True)), - ('publisher', models.TextField(default='', max_length=250)), - ('publication_date', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), + ('batch_year', models.CharField(max_length=10, unique=True)), + ('total_students', models.PositiveIntegerField(default=0)), + ('total_placed', models.PositiveIntegerField(default=0)), + ('total_companies', models.PositiveIntegerField(default=0)), + ('avg_ctc', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)), + ('highest_ctc', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)), + ('updated_at', models.DateTimeField(auto_now=True)), ], + options={ + 'verbose_name_plural': 'Placement Statistics', + 'ordering': ['-batch_year'], + }, ), migrations.CreateModel( - name='Project', + name='StudentPlacementProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('project_name', models.CharField(default='', max_length=50)), - ('project_status', models.CharField(choices=[('ONGOING', 'Ongoing'), ('COMPLETED', 'Completed')], default='COMPLETED', max_length=20)), - ('summary', models.TextField(blank=True, default='', max_length=1000, null=True)), - ('project_link', models.CharField(blank=True, default='', max_length=200, null=True)), - ('sdate', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('edate', models.DateField(blank=True, null=True)), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), + ('resume_url', models.URLField(blank=True)), + ('linkedin_url', models.URLField(blank=True)), + ('github_url', models.URLField(blank=True)), + ('is_placed', models.BooleanField(default=False)), + ('opted_out', models.BooleanField(default=False)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('student', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='placement_profile', to='globals.extrainfo')), ], ), migrations.CreateModel( name='PlacementSchedule', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('title', models.CharField(default='', max_length=100)), - ('placement_date', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('location', models.CharField(default='', max_length=100)), - ('description', models.TextField(blank=True, default='', max_length=500, null=True)), - ('time', models.TimeField()), - ('attached_file', models.FileField(blank=True, null=True, upload_to='documents/placement/schedule')), - ('schedule_at', models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True)), - ('notify_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='placement_cell.notifystudent')), - ('role', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='placement_cell.role')), - ], - ), - migrations.CreateModel( - name='Patent', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('patent_name', models.CharField(default='', max_length=100)), - ('description', models.TextField(blank=True, default='', max_length=250, null=True)), - ('patent_office', models.TextField(default='', max_length=250)), - ('patent_date', models.DateField()), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Interest', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('interest', models.CharField(default='', max_length=100)), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Extracurricular', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('event_name', models.CharField(default='', max_length=100)), - ('event_type', models.CharField(choices=[('SOCIAL', 'Social'), ('CULTURE', 'Culture'), ('SPORT', 'Sport'), ('OTHER', 'Other')], default='OTHER', max_length=20)), - ('description', models.TextField(blank=True, default='', max_length=1000, null=True)), - ('name_of_position', models.CharField(default='', max_length=200)), - ('date_earned', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Experience', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('title', models.CharField(default='', max_length=100)), - ('status', models.CharField(choices=[('ONGOING', 'Ongoing'), ('COMPLETED', 'Completed')], default='COMPLETED', max_length=20)), - ('description', models.TextField(blank=True, default='', max_length=500, null=True)), - ('company', models.CharField(default='', max_length=200)), - ('location', models.CharField(default='', max_length=200)), - ('sdate', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('edate', models.DateField(blank=True, null=True)), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Education', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('degree', models.CharField(default='', max_length=40)), - ('grade', models.CharField(default='', max_length=10)), - ('institute', models.TextField(default='', max_length=250)), - ('stream', models.CharField(blank=True, default='', max_length=150, null=True)), - ('sdate', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('edate', models.DateField(blank=True, null=True)), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Course', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('course_name', models.CharField(default='', max_length=100)), - ('description', models.TextField(blank=True, default='', max_length=250, null=True)), - ('license_no', models.CharField(blank=True, default='', max_length=100, null=True)), - ('sdate', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('edate', models.DateField(blank=True, null=True)), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Conference', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('conference_name', models.CharField(default='', max_length=100)), - ('description', models.TextField(blank=True, default='', max_length=250, null=True)), - ('sdate', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('edate', models.DateField(blank=True, null=True)), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='Coinventor', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('coinventor_name', models.CharField(default='', max_length=100)), - ('patent_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='placement_cell.patent')), - ], - ), - migrations.CreateModel( - name='Coauthor', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('coauthor_name', models.CharField(default='', max_length=100)), - ('publication_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='placement_cell.publication')), - ], - ), - migrations.CreateModel( - name='Achievement', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('achievement', models.CharField(default='', max_length=100)), - ('achievement_type', models.CharField(choices=[('EDUCATIONAL', 'Educational'), ('OTHER', 'Other')], default='OTHER', max_length=20)), - ('description', models.TextField(blank=True, default='', max_length=1000, null=True)), - ('issuer', models.CharField(default='', max_length=200)), - ('date_earned', models.DateField(default=datetime.date.today, verbose_name='Date')), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), - ], - ), - migrations.CreateModel( - name='StudentRecord', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('record_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='placement_cell.placementrecord')), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), + ('round_name', models.CharField(max_length=100)), + ('round_number', models.PositiveSmallIntegerField()), + ('scheduled_at', models.DateTimeField()), + ('venue', models.CharField(blank=True, max_length=200)), + ('notes', models.TextField(blank=True)), + ('job_post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='schedules', to='placement_cell.jobpost')), ], options={ - 'unique_together': {('record_id', 'unique_id')}, + 'ordering': ['round_number'], }, ), migrations.CreateModel( - name='PlacementStatus', + name='PlacementResult', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('invitation', models.CharField(choices=[('ACCEPTED', 'Accepted'), ('REJECTED', 'Rejected'), ('PENDING', 'Pending'), ('IGNORE', 'IGNORE')], default='PENDING', max_length=20)), - ('placed', models.CharField(choices=[('NOT PLACED', 'Not Placed'), ('PLACED', 'Placed')], default='NOT PLACED', max_length=20)), - ('timestamp', models.DateTimeField(auto_now=True)), - ('no_of_days', models.IntegerField(blank=True, default=10, null=True)), - ('notify_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='placement_cell.notifystudent')), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), + ('offer_date', models.DateField()), + ('joining_date', models.DateField(blank=True, null=True)), + ('ctc_offered', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)), + ('offer_letter', models.FileField(blank=True, upload_to='placement/offer_letters/')), + ('is_confirmed', models.BooleanField(default=False)), + ('application', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='result', to='placement_cell.placementapplication')), ], - options={ - 'unique_together': {('notify_id', 'unique_id')}, - }, ), migrations.CreateModel( - name='Has', + name='PlacementAnnouncement', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('skill_rating', models.IntegerField(default=80)), - ('skill_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='placement_cell.skill')), - ('unique_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='academic_information.student')), + ('title', models.CharField(max_length=300)), + ('body', models.TextField()), + ('posted_at', models.DateTimeField(auto_now_add=True)), + ('is_pinned', models.BooleanField(default=False)), + ('posted_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ], options={ - 'unique_together': {('skill_id', 'unique_id')}, + 'ordering': ['-is_pinned', '-posted_at'], }, ), ] diff --git a/FusionIIIT/applications/placement_cell/migrations/0002_auto_20260430_0802.py b/FusionIIIT/applications/placement_cell/migrations/0002_auto_20260430_0802.py new file mode 100644 index 000000000..8aad871af --- /dev/null +++ b/FusionIIIT/applications/placement_cell/migrations/0002_auto_20260430_0802.py @@ -0,0 +1,41 @@ +# Generated by Django 3.1.5 on 2026-04-30 08:02 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('globals', '0006_auto_20260304_0836'), + ('placement_cell', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='jobpost', + name='job_type', + field=models.CharField(choices=[('placement', 'Placement'), ('internship', 'Internship'), ('ppo', 'Pre Placement Offer')], default='placement', max_length=20), + ), + migrations.CreateModel( + name='OffCampusPlacement', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('company_name', models.CharField(max_length=255)), + ('role', models.CharField(max_length=200)), + ('offer_type', models.CharField(choices=[('placement', 'Placement'), ('internship', 'Internship')], default='placement', max_length=20)), + ('ctc', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)), + ('stipend', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)), + ('offer_date', models.DateField()), + ('notes', models.TextField(blank=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('added_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='added_offcampus_placements', to=settings.AUTH_USER_MODEL)), + ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='offcampus_placements', to='globals.extrainfo')), + ], + options={ + 'ordering': ['-offer_date'], + }, + ), + ] diff --git a/FusionIIIT/applications/placement_cell/migrations/0003_jobpost_apply_link.py b/FusionIIIT/applications/placement_cell/migrations/0003_jobpost_apply_link.py new file mode 100644 index 000000000..77fbf3705 --- /dev/null +++ b/FusionIIIT/applications/placement_cell/migrations/0003_jobpost_apply_link.py @@ -0,0 +1,18 @@ +# Generated by Django 3.1.5 on 2026-04-30 08:18 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('placement_cell', '0002_auto_20260430_0802'), + ] + + operations = [ + migrations.AddField( + model_name='jobpost', + name='apply_link', + field=models.URLField(blank=True), + ), + ] diff --git a/FusionIIIT/applications/placement_cell/models.py b/FusionIIIT/applications/placement_cell/models.py index 53f8d8ea4..bf0dad002 100644 --- a/FusionIIIT/applications/placement_cell/models.py +++ b/FusionIIIT/applications/placement_cell/models.py @@ -1,401 +1,172 @@ -import datetime -from django.db import models -from django.utils import timezone -from django.utils.translation import gettext as _ - -from applications.academic_information.models import Student - -# Class definations: - - -class Constants: - RESUME_TYPE = ( - ('ONGOING', 'Ongoing'), - ('COMPLETED', 'Completed'), - ) - - ACHIEVEMENT_TYPE = ( - ('EDUCATIONAL', 'Educational'), - ('OTHER', 'Other'), - ) - - EVENT_TYPE = ( - ('SOCIAL', 'Social'), - ('CULTURE', 'Culture'), - ('SPORT', 'Sport'), - ('OTHER', 'Other'), - ) - - INVITATION_TYPE = ( - ('ACCEPTED', 'Accepted'), - ('REJECTED', 'Rejected'), - ('PENDING', 'Pending'), - ('IGNORE', 'IGNORE'), - ) - - PLACEMENT_TYPE = ( - ('PLACEMENT', 'Placement'), - ('PBI', 'PBI'), - ('HIGHER STUDIES', 'Higher Studies'), - ('OTHER', 'Other'), - ) - - PLACED_TYPE = ( - ('NOT PLACED', 'Not Placed'), - ('PLACED', 'Placed'), - ) - - DEBAR_TYPE = ( - ('NOT DEBAR', 'Not Debar'), - ('DEBAR', 'Debar'), - ) - - BTECH_DEP = ( - ('CSE', 'CSE'), - ('ME','ME'), - ('ECE','ECE'), - ('SM','SM'), - ) - - BDES_DEP = ( - ('DESIGN', 'DESIGN'), - ) - - MTECH_DEP = ( - ('CSE', 'CSE'), - ('CAD/CAM', 'CAD/CAM'), - ('DESIGN', 'DESIGN'), - ('MANUFACTURING', 'MANUFACTURING'), - ('MECHATRONICS', 'MECHATRONICS'), - ) - - MDES_DEP = ( - ('DESIGN', 'DESIGN'), - ) - - PHD_DEP = ( - ('CSE', 'CSE'), - ('ME','ME'), - ('ECE','ECE'), - ('DESIGN', 'DESIGN'), - ('NS', 'NS'), - ) - - -class Project(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - project_name = models.CharField(max_length=50, default='') - project_status = models.CharField(max_length=20, choices=Constants.RESUME_TYPE, - default='COMPLETED') - summary = models.TextField(max_length=1000, default='', null=True, blank=True) - project_link = models.CharField(max_length=200, default='', null=True, blank=True) - sdate = models.DateField(_("Date"), default=datetime.date.today) - edate = models.DateField(null=True, blank=True) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.project_name) - - -class Skill(models.Model): - skill = models.CharField(max_length=30, default='') - - def __str__(self): - return self.skill - - -class Has(models.Model): - skill_id = models.ForeignKey(Skill, on_delete=models.CASCADE) - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - skill_rating = models.IntegerField(default=80) - - class Meta: - unique_together = (('skill_id', 'unique_id'),) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.skill_id.skill) - - -class Education(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - degree = models.CharField(max_length=40, default='') - grade = models.CharField(max_length=10, default='') - institute = models.TextField(max_length=250, default='') - stream = models.CharField(max_length=150, default='', null=True, blank=True) - sdate = models.DateField(_("Date"), default=datetime.date.today) - edate = models.DateField(null=True, blank=True) - - def clean(self): - - sdate = self.cleaned_data.get("startdate") - stime = self.cleaned_data.get("starttime") - print(sdate, "sdate") - today = datetime.datetime.now() - datetime.timedelta(1) - print(today, "today") - k1 = stime.hour - k2 = stime.minute - k3 = stime.second - x = time(k1, k2, k3) - date = datetime.datetime.combine(sdate, x) - edate = self.cleaned_data.get("enddate") - etime = self.cleaned_data.get("endtime") - k1 = etime.hour - k2 = etime.minute - k3 = etime.second - end_date = datetime.datetime.combine(edate, datetime.time(k1, k2, k3)) - print(date, end_date) - if(date < today): - raise forms.ValidationError("Invalid quiz Start Date") - elif(date > end_date): - raise forms.ValidationError("Start Date but me before End Date") - return self.cleaned_data - - -class Experience(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - title = models.CharField(max_length=100, default='') - status = models.CharField(max_length=20, choices=Constants.RESUME_TYPE, - default='COMPLETED') - description = models.TextField(max_length=500, default='', null=True, blank=True) - company = models.CharField(max_length=200, default='') - location = models.CharField(max_length=200, default='') - sdate = models.DateField(_("Date"), default=datetime.date.today) - edate = models.DateField(null=True, blank=True) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.company) - - -class Course(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - course_name = models.CharField(max_length=100, default='') - description = models.TextField(max_length=250, default='', null=True, blank=True) - license_no = models.CharField(max_length=100, default='', null=True, blank=True) - sdate = models.DateField(_("Date"), default=datetime.date.today) - edate = models.DateField(null=True, blank=True) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.course_name) - - -class Conference(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - conference_name = models.CharField(max_length=100, default='') - description = models.TextField(max_length=250, default='', null=True, blank=True) - sdate = models.DateField(_("Date"), default=datetime.date.today) - edate = models.DateField(null=True, blank=True) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.conference_name) - - -class Publication(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - publication_title = models.CharField(max_length=100, default='') - description = models.TextField(max_length=250, default='', null=True, blank=True) - publisher = models.TextField(max_length=250, default='') - publication_date = models.DateField(_("Date"), default=datetime.date.today) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.publication_title) - - -class Reference(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - reference_name = models.CharField(max_length=100, default='') - post = models.CharField(max_length=100, default='', null=True, blank=True) - email = models.CharField(max_length=50, default='') - mobile_number = models.CharField(max_length=15, blank=True, null=True) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.reference_name) - - -class Coauthor(models.Model): - publication_id = models.ForeignKey(Publication, on_delete=models.CASCADE) - coauthor_name = models.CharField(max_length=100, default='') - - def __str__(self): - return '{} - {}'.format(self.publication_id.publication_title, self.coauthor_name) - - -class Patent(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - patent_name = models.CharField(max_length=100, default='') - description = models.TextField(max_length=250, default='', null=True, blank=True) - patent_office = models.TextField(max_length=250, default='') - patent_date = models.DateField() - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.patent_name) - - -class Coinventor(models.Model): - patent_id = models.ForeignKey(Patent, on_delete=models.CASCADE) - coinventor_name = models.CharField(max_length=100, default='') - - def __str__(self): - return '{} - {}'.format(self.patent_id.patent_name, self.coinventor_name) - - -class Interest(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - interest = models.CharField(max_length=100, default='') - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.interest) - - -class Achievement(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - achievement = models.CharField(max_length=100, default='') - achievement_type = models.CharField(max_length=20, choices=Constants.ACHIEVEMENT_TYPE, - default='OTHER') - description = models.TextField(max_length=1000, default='', null=True, blank=True) - issuer = models.CharField(max_length=200, default='') - date_earned = models.DateField(_("Date"), default=datetime.date.today) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.achievement) - -class Extracurricular(models.Model): - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - event_name = models.CharField(max_length=100, default='') - event_type = models.CharField(max_length=20, choices=Constants.EVENT_TYPE, - default='OTHER') - description = models.TextField(max_length=1000, default='', null=True, blank=True) - name_of_position = models.CharField(max_length=200, default='') - date_earned = models.DateField(_("Date"), default=datetime.date.today) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.event_name) - - -class MessageOfficer(models.Model): - message = models.CharField(max_length=100, default='') - timestamp = models.DateTimeField(auto_now=True) - - def __str__(self): - return self.message - - -class NotifyStudent(models.Model): - placement_type = models.CharField(max_length=20, choices=Constants.PLACEMENT_TYPE, - default='PLACEMENT') - company_name = models.CharField(max_length=100, default='') - ctc = models.DecimalField(decimal_places=4, max_digits=10) - description = models.TextField(max_length=1000, default='', null=True, blank=True) - timestamp = models.DateTimeField(auto_now=True) - - def __str__(self): - return '{} - {}'.format(self.company_name, self.placement_type) - - @property - def get_placement_schedule_object(self): - return PlacementSchedule.objects.filter(notify_id=self.id).first() - - -class Role(models.Model): - role = models.CharField(max_length=100, blank=True, null=True) - - def __str__(self): - return self.role - -class CompanyDetails(models.Model): - company_name = models.CharField(max_length=100, blank=True, null=True) - - def __str__(self): - return self.company_name - - -class PlacementStatus(models.Model): - notify_id = models.ForeignKey(NotifyStudent, on_delete=models.CASCADE) - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - invitation = models.CharField(max_length=20, choices=Constants.INVITATION_TYPE, - default='PENDING') - placed = models.CharField(max_length=20, choices=Constants.PLACED_TYPE, - default='NOT PLACED') - timestamp = models.DateTimeField(auto_now=True) - no_of_days = models.IntegerField(default=10, null=True, blank=True) - - class Meta: - unique_together = (('notify_id', 'unique_id'),) - - @property - def response_date(self): - return self.timestamp+datetime.timedelta(days=self.no_of_days) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.notify_id.company_name) - - -class PlacementRecord(models.Model): - placement_type = models.CharField(max_length=20, choices=Constants.PLACEMENT_TYPE, - default='PLACEMENT') - name = models.CharField(max_length=100, default='') - ctc = models.DecimalField(decimal_places=2, max_digits=5, default=0) - year = models.IntegerField(default=0) - test_score = models.IntegerField(default=0, null=True, blank=True) - test_type = models.CharField(max_length=30, default='', null=True, blank=True) - - def __str__(self): - return '{} - {}'.format(self.name, self.year) - - -class StudentRecord(models.Model): - record_id = models.ForeignKey(PlacementRecord, on_delete=models.CASCADE) - unique_id = models.ForeignKey(Student, on_delete=models.CASCADE) - - class Meta: - unique_together = (('record_id', 'unique_id'),) - - def __str__(self): - return '{} - {}'.format(self.unique_id.id, self.record_id.name) - - -class ChairmanVisit(models.Model): - company_name = models.CharField(max_length=100, default='') - location = models.CharField(max_length=100, default='') - visiting_date = models.DateField(_("Date"), default=datetime.date.today) - description = models.TextField(max_length=1000, default='', null=True, blank=True) - timestamp = models.DateTimeField(auto_now=True) - - def __str__(self): - return self.company_name - - -class PlacementSchedule(models.Model): - notify_id = models.ForeignKey(NotifyStudent, on_delete=models.CASCADE) - title = models.CharField(max_length=100, default='') - placement_date = models.DateField(_("Date"), default=datetime.date.today) - location = models.CharField(max_length=100, default='') - description = models.TextField(max_length=500, default='', null=True, blank=True) - time = models.TimeField() - role = models.ForeignKey(Role, on_delete=models.CASCADE, null=True, blank=True) - attached_file = models.FileField(upload_to='documents/placement/schedule', null=True, blank=True) - schedule_at = models.DateTimeField(auto_now_add=False, auto_now=False, default=timezone.now, blank=True, null=True) - - def __str__(self): - return '{} - {}'.format(self.notify_id.company_name, self.placement_date) - - @property - def get_role(self): - try: - return self.role.role - except: - return '' - - -class StudentPlacement(models.Model): - unique_id = models.OneToOneField(Student, primary_key=True, on_delete=models.CASCADE) - debar = models.CharField(max_length=20, choices=Constants.DEBAR_TYPE, default='NOT DEBAR') - future_aspect = models.CharField(max_length=20, choices=Constants.PLACEMENT_TYPE, - default='PLACEMENT') - placed_type = models.CharField(max_length=20, choices=Constants.PLACED_TYPE, - default='NOT PLACED') - placement_date = models.DateField(_("Date"), default=datetime.date.today, null=True, - blank=True) - package = models.DecimalField(decimal_places=2, max_digits=5, null=True, - blank=True) - - def __str__(self): - return self.unique_id.id.id +from django.db import models +from django.contrib.auth.models import User + +from applications.globals.models import ExtraInfo + + +class Company(models.Model): + name = models.CharField(max_length=255, unique=True) + sector = models.CharField(max_length=100) + website = models.URLField(blank=True) + description = models.TextField(blank=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ['name'] + verbose_name_plural = 'Companies' + + def __str__(self): + return self.name + + +class JobPost(models.Model): + PLACEMENT = 'placement' + INTERNSHIP = 'internship' + PPO = 'ppo' + TYPE_CHOICES = [(PLACEMENT, 'Placement'), (INTERNSHIP, 'Internship'), (PPO, 'Pre Placement Offer')] + + company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='job_posts') + role = models.CharField(max_length=200) + job_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default=PLACEMENT) + description = models.TextField(blank=True) + ctc = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + stipend = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + location = models.CharField(max_length=200, blank=True) + eligible_batches = models.JSONField(default=list) + eligible_programmes = models.JSONField(default=list) + eligible_disciplines = models.JSONField(default=list) + min_cpi = models.DecimalField(max_digits=4, decimal_places=2, default=0.0) + apply_link = models.URLField(blank=True) + deadline = models.DateTimeField() + is_active = models.BooleanField(default=True) + created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='created_job_posts') + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ['-created_at'] + + def __str__(self): + return f"{self.company.name} — {self.role}" + + +class PlacementSchedule(models.Model): + job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE, related_name='schedules') + round_name = models.CharField(max_length=100) + round_number = models.PositiveSmallIntegerField() + scheduled_at = models.DateTimeField() + venue = models.CharField(max_length=200, blank=True) + notes = models.TextField(blank=True) + + class Meta: + ordering = ['round_number'] + + def __str__(self): + return f"{self.job_post} — Round {self.round_number}: {self.round_name}" + + +class PlacementApplication(models.Model): + APPLIED = 'applied' + SHORTLISTED = 'shortlisted' + REJECTED = 'rejected' + PLACED = 'placed' + WITHDRAWN = 'withdrawn' + STATUS_CHOICES = [ + (APPLIED, 'Applied'), + (SHORTLISTED, 'Shortlisted'), + (REJECTED, 'Rejected'), + (PLACED, 'Placed'), + (WITHDRAWN, 'Withdrawn'), + ] + + job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE, related_name='applications') + student = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE, related_name='placement_applications') + status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=APPLIED) + applied_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + unique_together = ('job_post', 'student') + ordering = ['-applied_at'] + + def __str__(self): + return f"{self.student} → {self.job_post} [{self.status}]" + + +class PlacementResult(models.Model): + application = models.OneToOneField(PlacementApplication, on_delete=models.CASCADE, related_name='result') + offer_date = models.DateField() + joining_date = models.DateField(null=True, blank=True) + ctc_offered = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + offer_letter = models.FileField(upload_to='placement/offer_letters/', blank=True) + is_confirmed = models.BooleanField(default=False) + + def __str__(self): + return f"Result: {self.application}" + + +class StudentPlacementProfile(models.Model): + student = models.OneToOneField(ExtraInfo, on_delete=models.CASCADE, related_name='placement_profile') + resume_url = models.URLField(blank=True) + linkedin_url = models.URLField(blank=True) + github_url = models.URLField(blank=True) + is_placed = models.BooleanField(default=False) + opted_out = models.BooleanField(default=False) + updated_at = models.DateTimeField(auto_now=True) + + def __str__(self): + return f"Profile: {self.student}" + + +class PlacementAnnouncement(models.Model): + title = models.CharField(max_length=300) + body = models.TextField() + posted_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) + posted_at = models.DateTimeField(auto_now_add=True) + is_pinned = models.BooleanField(default=False) + + class Meta: + ordering = ['-is_pinned', '-posted_at'] + + def __str__(self): + return self.title + + +class OffCampusPlacement(models.Model): + PLACEMENT = 'placement' + INTERNSHIP = 'internship' + TYPE_CHOICES = [(PLACEMENT, 'Placement'), (INTERNSHIP, 'Internship')] + + student = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE, related_name='offcampus_placements') + company_name = models.CharField(max_length=255) + role = models.CharField(max_length=200) + offer_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default=PLACEMENT) + ctc = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + stipend = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + offer_date = models.DateField() + notes = models.TextField(blank=True) + added_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, + related_name='added_offcampus_placements') + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ['-offer_date'] + + def __str__(self): + return f"{self.student} — {self.company_name} ({self.offer_type})" + + +class PlacementStatistics(models.Model): + batch_year = models.CharField(max_length=10, unique=True) + total_students = models.PositiveIntegerField(default=0) + total_placed = models.PositiveIntegerField(default=0) + total_companies = models.PositiveIntegerField(default=0) + avg_ctc = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + highest_ctc = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + verbose_name_plural = 'Placement Statistics' + ordering = ['-batch_year'] + + def __str__(self): + return f"Stats {self.batch_year}: {self.total_placed}/{self.total_students} placed" diff --git a/FusionIIIT/applications/placement_cell/selectors.py b/FusionIIIT/applications/placement_cell/selectors.py new file mode 100644 index 000000000..272992cd4 --- /dev/null +++ b/FusionIIIT/applications/placement_cell/selectors.py @@ -0,0 +1,146 @@ +""" +Read-only query layer. No writes happen here. +All CPI data is fetched live from the examination module. +""" +from decimal import Decimal +from django.utils import timezone + +from .models import ( + Company, JobPost, PlacementApplication, PlacementAnnouncement, + PlacementStatistics, StudentPlacementProfile, +) + + +def get_student_profile(student_extra_info) -> StudentPlacementProfile: + profile, _ = StudentPlacementProfile.objects.get_or_create(student=student_extra_info) + return profile + + +def get_student_published_cpi(student_extra_info): + """ + Returns the student's CPI calculated from the latest published semester result, + or None if no results have been published yet. + + Reuses calculation logic from the examination module to avoid duplication. + """ + try: + from applications.examination.models import ResultAnnouncement + from applications.examination.api.views import calculate_cpi_for_student + from applications.academic_information.models import Student + + student_obj = Student.objects.select_related('id').get(id=student_extra_info) + + latest = ( + ResultAnnouncement.objects + .filter(batch=student_obj.batch_id, announced=True) + .order_by('-semester') + .first() + ) + if not latest: + return None + + cpi_value, _, _ = calculate_cpi_for_student(student_obj, latest.semester, latest.semester_type) + return cpi_value + except Exception: + return None + + +def list_active_job_posts(student_extra_info=None): + """ + Returns active, non-expired job posts. + If student_extra_info is given, filters by eligibility (batch/programme/discipline). + """ + now = timezone.now() + qs = JobPost.objects.filter(is_active=True, deadline__gte=now).select_related('company') + + if student_extra_info is None: + return qs + + try: + from applications.academic_information.models import Student + student = Student.objects.select_related('batch_id__discipline_id', 'programme').get(id=student_extra_info) + batch_year = str(student.batch_id.year) if student.batch_id else None + programme = student.programme if student.programme else None + discipline = student.batch_id.discipline_id.acronym if student.batch_id and student.batch_id.discipline_id else None + + eligible = [] + for job in qs: + batch_ok = not job.eligible_batches or (batch_year and batch_year in job.eligible_batches) + programme_ok = not job.eligible_programmes or (programme and programme in job.eligible_programmes) + discipline_ok = not job.eligible_disciplines or (discipline and discipline in job.eligible_disciplines) + if batch_ok and programme_ok and discipline_ok: + eligible.append(job.pk) + return qs.filter(pk__in=eligible) + except Exception: + return qs + + +def list_job_posts_admin(): + return JobPost.objects.select_related('company').prefetch_related('schedules').all() + + +def get_job_post_detail(job_post_id: int) -> JobPost: + return JobPost.objects.select_related('company').prefetch_related('schedules').get(pk=job_post_id) + + +def list_applications_for_student(student_extra_info): + return ( + PlacementApplication.objects + .filter(student=student_extra_info) + .select_related('job_post__company') + .prefetch_related('job_post__schedules') + ) + + +def list_applications_for_job_post(job_post_id: int): + return ( + PlacementApplication.objects + .filter(job_post_id=job_post_id) + .select_related('student__user', 'job_post__company') + ) + + +def list_all_applications_admin(filters: dict = None): + qs = PlacementApplication.objects.select_related('student__user', 'job_post__company') + if filters: + if filters.get('job_post_id'): + qs = qs.filter(job_post_id=filters['job_post_id']) + if filters.get('status'): + qs = qs.filter(status=filters['status']) + return qs + + +def list_announcements(): + return PlacementAnnouncement.objects.all() + + +def list_companies(): + return Company.objects.all() + + +def get_placement_statistics(batch_year: str = None): + if batch_year: + try: + return PlacementStatistics.objects.get(batch_year=batch_year) + except PlacementStatistics.DoesNotExist: + return None + return PlacementStatistics.objects.all() + + +def export_placement_data_rows(filters: dict = None) -> list: + """Returns serializable row dicts for Excel export.""" + qs = list_all_applications_admin(filters) + rows = [] + for app in qs: + u = app.student.user + rows.append({ + 'roll_no': u.username, + 'name': f"{u.first_name} {u.last_name}".strip(), + 'email': u.email, + 'company': app.job_post.company.name, + 'role': app.job_post.role, + 'job_type': app.job_post.job_type, + 'status': app.status, + 'applied_at': app.applied_at.strftime('%Y-%m-%d') if app.applied_at else '', + }) + return rows diff --git a/FusionIIIT/applications/placement_cell/services.py b/FusionIIIT/applications/placement_cell/services.py new file mode 100644 index 000000000..180081407 --- /dev/null +++ b/FusionIIIT/applications/placement_cell/services.py @@ -0,0 +1,200 @@ +""" +Write-only business logic layer. +All DB writes happen here. Views call these functions after validation. +""" +from django.db import transaction +from django.utils import timezone +from django.core.exceptions import ValidationError + +from .models import ( + Company, JobPost, OffCampusPlacement, PlacementApplication, PlacementAnnouncement, + PlacementResult, PlacementStatistics, StudentPlacementProfile, +) +from .selectors import get_student_published_cpi, get_student_profile + + +# ---------- Company ---------- + +def create_company(data: dict) -> Company: + return Company.objects.create(**data) + + +def update_company(company_id: int, data: dict) -> Company: + Company.objects.filter(pk=company_id).update(**data) + return Company.objects.get(pk=company_id) + + +def delete_company(company_id: int) -> None: + Company.objects.filter(pk=company_id).delete() + + +# ---------- Job Post ---------- + +def create_job_post(data: dict, created_by_user) -> JobPost: + data = dict(data) + data['created_by'] = created_by_user + return JobPost.objects.create(**data) + + +def update_job_post(job_post_id: int, data: dict) -> JobPost: + JobPost.objects.filter(pk=job_post_id).update(**data) + return JobPost.objects.select_related('company').get(pk=job_post_id) + + +def toggle_job_post_active(job_post_id: int) -> JobPost: + job = JobPost.objects.get(pk=job_post_id) + job.is_active = not job.is_active + job.save(update_fields=['is_active']) + return job + + +# ---------- Application ---------- + +def apply_to_job(student_extra_info, job_post_id: int) -> PlacementApplication: + job = JobPost.objects.select_related('company').get(pk=job_post_id) + + if not job.is_active: + raise ValidationError("This job post is no longer active.") + if timezone.now() > job.deadline: + raise ValidationError("The application deadline has passed.") + + if PlacementApplication.objects.filter(job_post=job, student=student_extra_info).exists(): + raise ValidationError("You have already applied to this job post.") + + profile = get_student_profile(student_extra_info) + if profile.is_placed: + raise ValidationError("You are already placed and cannot apply to more openings.") + + if job.min_cpi > 0: + cpi = get_student_published_cpi(student_extra_info) + if cpi is None or cpi < job.min_cpi: + raise ValidationError( + f"Your published CPI does not meet the minimum requirement of {job.min_cpi}." + ) + + return PlacementApplication.objects.create(job_post=job, student=student_extra_info) + + +def withdraw_application(application_id: int, student_extra_info) -> None: + app = PlacementApplication.objects.get(pk=application_id, student=student_extra_info) + if app.status == PlacementApplication.PLACED: + raise ValidationError("Cannot withdraw a confirmed placement offer.") + app.status = PlacementApplication.WITHDRAWN + app.save(update_fields=['status', 'updated_at']) + + +def update_application_status(application_id: int, new_status: str) -> PlacementApplication: + valid = {s for s, _ in PlacementApplication.STATUS_CHOICES} + if new_status not in valid: + raise ValidationError(f"Invalid status '{new_status}'.") + app = PlacementApplication.objects.select_related('student', 'job_post').get(pk=application_id) + app.status = new_status + app.save(update_fields=['status', 'updated_at']) + + if new_status == PlacementApplication.PLACED: + profile, _ = StudentPlacementProfile.objects.get_or_create(student=app.student) + if not profile.is_placed: + profile.is_placed = True + profile.save(update_fields=['is_placed']) + + return app + + +def bulk_update_application_status(application_ids: list, new_status: str) -> int: + valid = {s for s, _ in PlacementApplication.STATUS_CHOICES} + if new_status not in valid: + raise ValidationError(f"Invalid status '{new_status}'.") + + with transaction.atomic(): + updated = PlacementApplication.objects.filter(pk__in=application_ids).update( + status=new_status, + updated_at=timezone.now(), + ) + if new_status == PlacementApplication.PLACED: + student_ids = list( + PlacementApplication.objects.filter(pk__in=application_ids).values_list('student_id', flat=True) + ) + StudentPlacementProfile.objects.filter(student_id__in=student_ids).update(is_placed=True) + + return updated + + +# ---------- Student Profile ---------- + +def upsert_student_profile(student_extra_info, data: dict) -> StudentPlacementProfile: + allowed = {'resume_url', 'linkedin_url', 'github_url', 'opted_out'} + clean = {k: v for k, v in data.items() if k in allowed} + profile, _ = StudentPlacementProfile.objects.get_or_create(student=student_extra_info) + # opted_out is one-way: once True it cannot be reverted via API + if profile.opted_out: + clean.pop('opted_out', None) + for k, v in clean.items(): + setattr(profile, k, v) + profile.save() + return profile + + +# ---------- Off-Campus Placements ---------- + +def add_offcampus_placement(data: dict, added_by_user) -> OffCampusPlacement: + data = dict(data) + data['added_by'] = added_by_user + ocp = OffCampusPlacement.objects.create(**data) + profile, _ = StudentPlacementProfile.objects.get_or_create(student=ocp.student) + if not profile.is_placed: + profile.is_placed = True + profile.save(update_fields=['is_placed']) + return ocp + + +def delete_offcampus_placement(placement_id: int) -> None: + OffCampusPlacement.objects.filter(pk=placement_id).delete() + + +# ---------- Announcements ---------- + +def create_announcement(data: dict, posted_by_user) -> PlacementAnnouncement: + return PlacementAnnouncement.objects.create(posted_by=posted_by_user, **data) + + +def delete_announcement(announcement_id: int) -> None: + PlacementAnnouncement.objects.filter(pk=announcement_id).delete() + + +# ---------- Statistics ---------- + +def refresh_statistics(batch_year: str) -> PlacementStatistics: + from applications.academic_information.models import Student + + students = Student.objects.filter(batch_id__year=batch_year) + total = students.count() + + placed_apps = PlacementApplication.objects.filter( + student__user__username__in=students.values_list('id__user__username', flat=True), + status=PlacementApplication.PLACED, + ).select_related('result') + + placed = placed_apps.count() + companies = ( + placed_apps.values('job_post__company').distinct().count() + ) + + ctc_values = [ + app.result.ctc_offered + for app in placed_apps + if hasattr(app, 'result') and app.result.ctc_offered is not None + ] + avg_ctc = sum(ctc_values) / len(ctc_values) if ctc_values else None + highest_ctc = max(ctc_values) if ctc_values else None + + stats, _ = PlacementStatistics.objects.update_or_create( + batch_year=batch_year, + defaults={ + 'total_students': total, + 'total_placed': placed, + 'total_companies': companies, + 'avg_ctc': avg_ctc, + 'highest_ctc': highest_ctc, + }, + ) + return stats diff --git a/FusionIIIT/applications/placement_cell/templatetags/pdf_filters.py b/FusionIIIT/applications/placement_cell/templatetags/pdf_filters.py deleted file mode 100644 index 5d35dca0b..000000000 --- a/FusionIIIT/applications/placement_cell/templatetags/pdf_filters.py +++ /dev/null @@ -1,18 +0,0 @@ -import base64 -import io -import urllib - -from django import template - -register = template.Library() - -@register.filter -def get64(url): - """ - Method returning base64 image data instead of URL - """ - if url.startswith("http"): - image = io.StringIO(urllib.urlopen(url).read()) - return 'data:image/jpg;base64,' + base64.b64encode(image.read()) - - return url diff --git a/FusionIIIT/applications/placement_cell/tests.py b/FusionIIIT/applications/placement_cell/tests.py deleted file mode 100644 index e9137c85e..000000000 --- a/FusionIIIT/applications/placement_cell/tests.py +++ /dev/null @@ -1,3 +0,0 @@ -# from django.test import TestCase - -# Create your tests here. diff --git a/FusionIIIT/applications/placement_cell/tests/__init__.py b/FusionIIIT/applications/placement_cell/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/FusionIIIT/applications/placement_cell/tests/test_module.py b/FusionIIIT/applications/placement_cell/tests/test_module.py new file mode 100644 index 000000000..7426f6130 --- /dev/null +++ b/FusionIIIT/applications/placement_cell/tests/test_module.py @@ -0,0 +1,185 @@ +""" +Placement Cell — unit and integration tests. + +Run with: python manage.py test applications.placement_cell.tests +""" +from datetime import timedelta +from decimal import Decimal +from unittest.mock import patch + +from django.contrib.auth.models import User +from django.test import TestCase +from django.utils import timezone +from rest_framework.test import APIClient + +from applications.globals.models import Designation, ExtraInfo, HoldsDesignation +from applications.placement_cell.models import ( + Company, JobPost, PlacementApplication, StudentPlacementProfile, +) +from applications.placement_cell import services, selectors + + +# ─── helpers ──────────────────────────────────────────────────────────────── + +def _make_user(username, role='student'): + user = User.objects.create_user(username=username, password='testpass123') + extra, _ = ExtraInfo.objects.get_or_create(user=user, defaults={'user_type': role}) + designation, _ = Designation.objects.get_or_create(name=role) + HoldsDesignation.objects.get_or_create(user=user, designation=designation, working=user) + return user, extra + + +def _make_company(name='Acme Corp'): + return Company.objects.create(name=name, sector='IT') + + +def _make_job(company, days_until_deadline=7, min_cpi=Decimal('0.0')): + return JobPost.objects.create( + company=company, + role='SDE', + job_type=JobPost.PLACEMENT, + min_cpi=min_cpi, + deadline=timezone.now() + timedelta(days=days_until_deadline), + is_active=True, + ) + + +# ─── Service tests ─────────────────────────────────────────────────────────── + +class ApplyToJobServiceTests(TestCase): + + def setUp(self): + _, self.extra = _make_user('stu01') + company = _make_company() + self.job = _make_job(company) + + def test_successful_application(self): + app = services.apply_to_job(self.extra, self.job.pk) + self.assertEqual(app.status, PlacementApplication.APPLIED) + + def test_duplicate_application_raises(self): + services.apply_to_job(self.extra, self.job.pk) + with self.assertRaises(Exception) as ctx: + services.apply_to_job(self.extra, self.job.pk) + self.assertIn('already applied', str(ctx.exception).lower()) + + def test_expired_deadline_raises(self): + job = _make_job(_make_company('OldCo'), days_until_deadline=-1) + with self.assertRaises(Exception) as ctx: + services.apply_to_job(self.extra, job.pk) + self.assertIn('deadline', str(ctx.exception).lower()) + + def test_inactive_job_raises(self): + self.job.is_active = False + self.job.save() + with self.assertRaises(Exception) as ctx: + services.apply_to_job(self.extra, self.job.pk) + self.assertIn('active', str(ctx.exception).lower()) + + @patch('applications.placement_cell.selectors.get_student_published_cpi') + def test_low_cpi_raises(self, mock_cpi): + mock_cpi.return_value = Decimal('6.0') + job = _make_job(_make_company('HighBarCo'), min_cpi=Decimal('7.5')) + with self.assertRaises(Exception) as ctx: + services.apply_to_job(self.extra, job.pk) + self.assertIn('cpi', str(ctx.exception).lower()) + + @patch('applications.placement_cell.selectors.get_student_published_cpi') + def test_sufficient_cpi_succeeds(self, mock_cpi): + mock_cpi.return_value = Decimal('8.5') + job = _make_job(_make_company('GoodCo'), min_cpi=Decimal('7.5')) + app = services.apply_to_job(self.extra, job.pk) + self.assertIsNotNone(app.pk) + + def test_placed_student_cannot_apply(self): + StudentPlacementProfile.objects.create(student=self.extra, is_placed=True) + with self.assertRaises(Exception) as ctx: + services.apply_to_job(self.extra, self.job.pk) + self.assertIn('placed', str(ctx.exception).lower()) + + +class BulkStatusUpdateTests(TestCase): + + def setUp(self): + _, extra1 = _make_user('stu02') + _, extra2 = _make_user('stu03') + company = _make_company('BulkCo') + job = _make_job(company) + self.app1 = PlacementApplication.objects.create(job_post=job, student=extra1) + self.app2 = PlacementApplication.objects.create(job_post=job, student=extra2) + + def test_bulk_shortlist(self): + count = services.bulk_update_application_status( + [self.app1.pk, self.app2.pk], PlacementApplication.SHORTLISTED + ) + self.assertEqual(count, 2) + self.app1.refresh_from_db() + self.assertEqual(self.app1.status, PlacementApplication.SHORTLISTED) + + def test_invalid_status_raises(self): + with self.assertRaises(Exception): + services.bulk_update_application_status([self.app1.pk], 'invalid_status') + + +# ─── Selector tests ────────────────────────────────────────────────────────── + +class SelectorTests(TestCase): + + def test_list_active_jobs_excludes_expired(self): + company = _make_company('ExpiredCo') + _make_job(company, days_until_deadline=-1) + jobs = list(selectors.list_active_job_posts()) + self.assertEqual(len(jobs), 0) + + def test_list_active_jobs_includes_future(self): + company = _make_company('FutureCo') + _make_job(company, days_until_deadline=5) + jobs = list(selectors.list_active_job_posts()) + self.assertEqual(len(jobs), 1) + + @patch('applications.placement_cell.selectors.get_student_published_cpi') + def test_get_student_published_cpi_none_when_no_results(self, mock_inner): + mock_inner.return_value = None + result = selectors.get_student_published_cpi(None) + self.assertIsNone(result) + + def test_get_student_profile_creates_if_missing(self): + _, extra = _make_user('stu04') + self.assertFalse(StudentPlacementProfile.objects.filter(student=extra).exists()) + profile = selectors.get_student_profile(extra) + self.assertIsNotNone(profile.pk) + + +# ─── API permission tests ──────────────────────────────────────────────────── + +class APIPermissionTests(TestCase): + + def setUp(self): + self.client = APIClient() + self.student_user, _ = _make_user('api_stu', 'student') + self.officer_user, _ = _make_user('api_ofc', 'placement_officer') + + def _auth(self, user): + from rest_framework.authtoken.models import Token + token, _ = Token.objects.get_or_create(user=user) + self.client.credentials(HTTP_AUTHORIZATION=f'Token {token.key}') + + def test_student_cannot_access_officer_jobs(self): + self._auth(self.student_user) + resp = self.client.get('/placement-cell/api/officer/jobs/') + self.assertEqual(resp.status_code, 403) + + def test_officer_can_access_officer_jobs(self): + self._auth(self.officer_user) + resp = self.client.get('/placement-cell/api/officer/jobs/') + self.assertEqual(resp.status_code, 200) + + def test_student_can_access_student_jobs(self): + self._auth(self.student_user) + resp = self.client.get('/placement-cell/api/stu/jobs/') + self.assertEqual(resp.status_code, 200) + + def test_unauthenticated_rejected(self): + self.client.credentials() + resp = self.client.get('/placement-cell/api/stu/jobs/') + self.assertIn(resp.status_code, [401, 403]) diff --git a/FusionIIIT/applications/placement_cell/urls.py b/FusionIIIT/applications/placement_cell/urls.py deleted file mode 100644 index 190638861..000000000 --- a/FusionIIIT/applications/placement_cell/urls.py +++ /dev/null @@ -1,29 +0,0 @@ -from django.conf.urls import url -from . import views - -app_name = 'placement' - -urlpatterns = [ - url(r'^$', views.placement, name='placement'), - url(r'^get_reference_list/$', views.get_reference_list, name='get_reference_list'), - url(r'^checking_roles/$', views.checking_roles, name='checking_roles'), - url(r'^companyname_dropdown/$', views.company_name_dropdown, name='companyname_dropdown'), - url(r'^student_records/invitation_status$', views.invitation_status, name='invitation_status'), - url(r'^student_records/delete_invitation_status$', views.delete_invitation_status, name='delete_invitation_status'), - url(r'^student_records/$', views.student_records, name='student_records'), - url(r'^manage_records/$', views.manage_records, name='manage_records'), - url(r'^statistics/$', views.placement_statistics, name='placement_statistics'), - - url(r'^delete_placement_statistics/$', views.delete_placement_statistics, name='delete_placement_statistics'), - url(r'^cv/(?P[a-zA-Z0-9\.]{1,20})/$', views.cv, name="cv"), - - - #added new url - url(r'^add_placement_schedule/$', views.add_placement_schedule, name='add_placement_schedule'), - url(r'^placement_schedule_save/$', views.placement_schedule_save, name='placement_schedule_save'), - url(r'^delete_placement_record/$', views.delete_placement_record, name='delete_placement_record'), - url(r'^add_placement_record/$', views.add_placement_record, name='add_placement_record'), - url(r'^placement_record_save/$', views.placement_record_save, name='placement_record_save'), - url(r'^add_placement_visit/$', views.add_placement_visit, name='add_placement_visit'), - url(r'^placement_visit_save/$', views.placement_visit_save, name='placement_visit_save'), -] diff --git a/FusionIIIT/applications/placement_cell/views.py b/FusionIIIT/applications/placement_cell/views.py deleted file mode 100644 index 25ecadebd..000000000 --- a/FusionIIIT/applications/placement_cell/views.py +++ /dev/null @@ -1,5810 +0,0 @@ -import os -import shutil -import datetime -import decimal -import zipfile -import xlwt -import logging - -from html import escape -from datetime import date -from io import BytesIO -from wsgiref.util import FileWrapper -from django.conf import settings -from django.contrib.auth.decorators import login_required -from django.contrib.auth.models import User -from django.contrib import messages -from django.core.cache import cache -from django.core.files.storage import FileSystemStorage -from django.core.paginator import Paginator -from django.db.models import Count, Q -from django.http import HttpResponse, JsonResponse -from django.shortcuts import get_object_or_404, redirect, render -from django.template.loader import get_template, render_to_string -from django.utils import timezone -from django.utils.encoding import smart_str -from xhtml2pdf import pisa -from django.core import serializers -from applications.academic_information.models import Student -from notification.views import placement_cell_notif -from applications.globals.models import (DepartmentInfo, ExtraInfo, - HoldsDesignation) -from applications.academic_information.models import Student -from .forms import (AddAchievement, AddChairmanVisit, AddCourse, AddEducation, - AddExperience, AddReference, AddPatent, AddProfile, AddProject, - AddPublication, AddSchedule, AddSkill, ManageHigherRecord, - ManagePbiRecord, ManagePlacementRecord, SearchHigherRecord, - SearchPbiRecord, SearchPlacementRecord, - SearchStudentRecord, SendInvite) - -from .models import (Achievement, ChairmanVisit, Course, Education, Experience, Conference, - Has, NotifyStudent, Patent, PlacementRecord, Extracurricular, Reference, - PlacementSchedule, PlacementStatus, Project, Publication, - Skill, StudentPlacement, StudentRecord, Role, CompanyDetails,) -''' - @variables: - user - logged in user - profile - variable for extrainfo - studentrecord - storing all fetched student record from database - years - yearwise record of student placement - records - all the record of placement record table - tcse - all record of cse - tece - all record of ece - tme - all record of me - tadd - all record of student - form respective form object - stuname - student name obtained from the form - ctc - salary offered obtained from the form - cname - company name obtained from the form - rollno - roll no of student obtained from the form - year - year of placement obtained from the form - s - extra info data of the student obtained from the form - p - placement data of the student obtained from the form - placementrecord - placement record of the student obtained from the form - pbirecord - pbi data of the student obtained from the form - test_type - type of higher study test obtained from the form - uname - name of universty obtained from the form - test_score - score in the test obtained from the form - higherrecord - higher study record of the student obtained from the form - current - current user on a particular designation - status - status of the sent invitation by placement cell regarding placement/pbi - institute - institute for previous education obtained from the form - degree - degree for previous education obtained from the form - grade - grade for previous education obtained from the form - stream - stream for previous education obtained from the form - sdate - start date for previous education obtained from the form - edate - end date for previous education obtained from the form - education_obj - object variable of Education table - about_me - about me data obtained from the form - age - age data obtained from the form - address - address obtained from the form - contact - contact obtained from the form - pic - picture obtained from the form - skill - skill of the user obtained from the form - skill_rating - rating of respective skill obtained from the form - has_obj - object variable of Has table - achievement - achievement of user obtained from the form - achievement_type - type of achievement obtained from the form - description - description of respective achievement obtained from the form - issuer - certifier of respective achievement obtained from the form - date_earned - date of the respective achievement obtained from the form - achievement_obj - object variable of Achievement table - publication_title - title of the publication obtained from the form - description - description of respective publication obtained from the form - publisher - publisher of respective publication obtained from the form - publication_date - date of respective publication obtained from the form - publication_obj - object variable of Publication table - patent_name - name of patent obtained from the form - description - description of respective patent obtained from the form - patent_office - office of respective patent obtained from the form - patent_date - date of respective patent obtained from the form - patent_obj - object variable of Patent table - course_name - name of the course obtained from the form - description description of respective course obtained from the form - license_no - license_no of respective course obtained from the form - sdate - start date of respective course obtained from the form - edate - end date of respective course obtained from the form - course_obj - object variable of Course table - project_name - name of project obtained from the form - project_status - status of respective project obtained from the form - summary - summery of the respective project obtained from the form - project_link - link of the respective project obtained from the form - sdate - start date of respective project obtained from the form - edate - end date of respective project obtained from the form - project_obj - object variable of Project table - title - title of any kind of experience obtained from the form - status - status of the respective experience obtained from the form - company - company from which respective experience is gained as obtained from the form - location - location of the respective experience obtained from the form - description - description of respective experience obtained from the form - sdate - start date of respective experience obtained from the form - edate - end date of respective experience obtained from the form - experience_obj - object variable of Experience table - context - to sent the relevant context for html rendering - company_name - name of visiting comapany obtained from the form - location -location of visiting company obtained from the form - description - description of respective company obtained from the form - visiting_date - visiting date of respective company obtained from the form - visit_obj -object variable of ChairmanVisit table - notify - object of NotifyStudent table - schedule - object variable of PlacementSchedule table - q1 - all data of Has table - q3 - all data of Student table - st - all data of Student table - spid - id of student to be debar - sr - record from StudentPlacement of student having id=spid - achievementcheck - checking for achievent to be shown in cv - educationcheck - checking for education to be shown in cv - publicationcheck - checking for publication to be shown in cv - patentcheck - checking for patent to be shown in cv - internshipcheck - checking for internship to be shown in cv - projectcheck - checking for project to be shown in cv - coursecheck - checking for course to be shown in cv - skillcheck - checking for skill to be shown in cv -''' - -logger = logging.getLogger('django.server') -@login_required -def placement__Statistics(request): - ''' - logic of the view shown under Placement Statistics tab - ''' - user = request.user - - - statistics_tab = 1 - strecord_tab=1 - delete_operation = 0 - pagination_placement = 0 - pagination_pbi = 0 - pagination_higher = 0 - is_disabled = 0 - paginator = '' - page_range = '' - officer_statistics_past_pbi_search = 0 - officer_statistics_past_higher_search = 0 - - profile = get_object_or_404(ExtraInfo, Q(user=user)) - studentrecord = StudentRecord.objects.select_related('unique_id','record_id').all() - - years = PlacementRecord.objects.filter(~Q(placement_type="HIGHER STUDIES")).values('year').annotate(Count('year')) - records = PlacementRecord.objects.values('name', 'year', 'ctc', 'placement_type').annotate(Count('name'), Count('year'), Count('placement_type'), Count('ctc')) - - - - - #working here to fetch all placement record - all_records=PlacementRecord.objects.all() - print(all_records) - - - - - - - invitecheck=0 - for r in records: - r['name__count'] = 0 - r['year__count'] = 0 - r['placement_type__count'] = 0 - tcse = dict() - tece = dict() - tme = dict() - tadd = dict() - for y in years: - tcse[y['year']] = 0 - tece[y['year']] = 0 - tme[y['year']] = 0 - for r in records: - if r['year'] == y['year']: - if r['placement_type'] != "HIGHER STUDIES": - for z in studentrecord: - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "CSE": - tcse[y['year']] = tcse[y['year']]+1 - r['name__count'] = r['name__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ECE": - tece[y['year']] = tece[y['year']]+1 - r['year__count'] = r['year__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ME": - tme[y['year']] = tme[y['year']]+1 - r['placement_type__count'] = r['placement_type__count']+1 - tadd[y['year']] = tcse[y['year']]+tece[y['year']]+tme[y['year']] - y['year__count'] = [tadd[y['year']], tcse[y['year']], tece[y['year']], tme[y['year']]] - - form2 = SearchPlacementRecord(initial={}) - form3 = SearchPbiRecord(initial={}) - form4 = SearchHigherRecord(initial={}) - - - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - - if len(current1)!=0 or len(current2)!=0: - delete_operation = 1 - if len(current) == 0: - current = None - pbirecord= '' - placementrecord= '' - higherrecord= '' - total_query=0 - total_query1 = 0 - total_query2= 0 - p="" - p1="" - p2="" - placement_search_record=" " - pbi_search_record=" " - higher_search_record=" " - # results of the searched query under placement tab - if 'studentplacementrecordsubmit' in request.POST: - officer_statistics_past = 1 - form = SearchPlacementRecord(request.POST) - if form.is_valid(): - - - - - print("IS VALID") - - - - #for student name - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except Exception as e: - print("Error") - print(e) - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - - - # for student CTC - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - - #for company name - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - - #for student roll - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - #for admission year - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - - - - - """placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name, - id__icontains=rollno)))))))) - #print("In if:", placementrecord) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)) - print("Agein p:",p) - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno))))))) - - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - print(p) - - - total_query = p.count() - - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - s = Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])) - - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except Exception as e: - print(e) - placementrecord = '' - - if placementrecord != '': - total_query = placementrecord.count() - else: - total_query = 0 - no_records=1 - print(placementrecord) - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - placementrecord = '' - - if total_query!=0: - placement_search_record=p - # results of the searched query under pbi tab - if 'studentpbirecordsubmit' in request.POST: - officer_statistics_past_pbi_search = 1 - form = SearchPbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - p1 = PlacementRecord.objects.filter( - Q(placement_type="PBI", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - """else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] -""" - total_query1 = p1.count() - - if total_query1 > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query1 > 30 and total_query1 <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=ctc, year=request.session['year'])), - unique_id__in=Student.objects.filter(( - Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter(Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except: - print('except') - pbirecord = '' - - if pbirecord != '': - total_query = pbirecord.count() - else: - total_query = 0 - - if total_query > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - pbirecord = '' - if total_query1!=0: - pbi_search_record=p1 - - # results of the searched query under higher studies tab - if 'studenthigherrecordsubmit' in request.POST: - officer_statistics_past_higher_search = 1 - form = SearchHigherRecord(request.POST) - if form.is_valid(): - # getting all the variables send through form - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['test_type']: - test_type = form.cleaned_data['test_type'] - else: - test_type = '' - if form.cleaned_data['uname']: - uname = form.cleaned_data['uname'] - else: - uname = '' - if form.cleaned_data['test_score']: - test_score = form.cleaned_data['test_score'] - else: - test_score = 0 - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - # result of the query when year is given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, year=year, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - - p2 = PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", name__icontains=stuname, year__icontains=year)) - - """else: - # result of the query when year is not given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['test_score'] = test_score - request.session['uname'] = uname - request.session['test_type'] = test_type - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - total_query2 = p2.count() - - if total_query2 > 30: - pagination_higher = 1 - paginator = Paginator(p2, 30) - page = request.GET.get('page', 1) - p2 = paginator.page(page) - page = int(page) - total_page = int(page+3) - - if page < (paginator.num_pages-3): - if total_query2 > 30 and total_query2 <= 60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(page-2, paginator.num_pages+1) - else: - pagination_higher = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - year=request.session['year'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - else: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - except: - higherrecord = '' - - if higherrecord != '': - total_query = higherrecord.count() - else: - total_query = 0 - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(higherrecord, 30) - page = request.GET.get('page', 1) - higherrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - higherrecord = '' - if total_query2!=0: - higher_search_record=p2 - - context = { - 'form2' : form2, - 'form3' : form3, - 'form4' : form4, - 'current' : current, - 'current1' : current1, - 'current2' : current2, - - - 'all_records': all_records, #for flashing all placement Schedule - - 'placement_search_record': placement_search_record, - 'pbi_search_record': pbi_search_record, - 'higher_search_record': higher_search_record, - - - - 'statistics_tab' : statistics_tab, - 'pbirecord' : pbirecord, - 'placementrecord' : placementrecord, - 'higherrecord' : higherrecord, - 'years' : years, - 'records' : records, - 'delete_operation' : delete_operation, - 'page_range': page_range, - 'paginator': paginator, - 'pagination_placement': pagination_placement, - 'pagination_pbi': pagination_pbi, - 'pagination_higher': pagination_higher, - 'is_disabled': is_disabled, - 'officer_statistics_past_pbi_search': officer_statistics_past_pbi_search, - 'officer_statistics_past_higher_search': officer_statistics_past_higher_search - } - - return render(request, 'placementModule/placementstatistics.html', context) - - - -def get_reference_list(request): - if request.method == 'POST': - # arr = request.POST.getlist('arr[]') - # print(arr) - # print(type(arr)) - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - student = get_object_or_404(Student, Q(id=profile.id)) - print(student) - reference_objects = Reference.select_related('unique_id').objects.filter(unique_id=student) - reference_objects = serializers.serialize('json', list(reference_objects)) - - context = { - 'reference_objs': reference_objects - } - return JsonResponse(context) - - -# Ajax for the company name dropdown for CompanyName when filling AddSchedule -def company_name_dropdown(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - company_names = CompanyDetails.objects.filter(Q(company_name__startswith=current_value)) - company_name = [] - for name in company_names: - company_name.append(name.company_name) - - context = { - 'company_names': company_name - } - - return JsonResponse(context) - - -# Ajax for all the roles in the dropdown -def checking_roles(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - all_roles = Role.objects.filter(Q(role__startswith=current_value)) - role_name = [] - for role in all_roles: - role_name.append(role.role) - return JsonResponse({'all_roles': role_name}) - -@login_required -def Placement__Schedule(request): - ''' - function include the functionality of first tab of UI - for student, placement officer & placement chairman - - placement officer & placement chairman - - can add schedule - - can delete schedule - student - - accepted or declined schedule - - ''' - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - schedule_tab = 1 - placementstatus = '' - - - form5 = AddSchedule(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - # If the user is Student - if current: - student = get_object_or_404(Student, Q(id=profile.id)) - - # Student view for showing accepted or declined schedule - if request.method == 'POST': - if 'studentapprovesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - pk=request.POST['studentapprovesubmit']).update( - invitation='ACCEPTED', - timestamp=timezone.now()) - if 'studentdeclinesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(pk=request.POST['studentdeclinesubmit'])).update( - invitation='REJECTED', - timestamp=timezone.now()) - - if 'educationsubmit' in request.POST: - form = AddEducation(request.POST) - if form.is_valid(): - institute = form.cleaned_data['institute'] - degree = form.cleaned_data['degree'] - grade = form.cleaned_data['grade'] - stream = form.cleaned_data['stream'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - education_obj = Education.objects.select_related('unique_id').create( - unique_id=student, degree=degree, - grade=grade, institute=institute, - stream=stream, sdate=sdate, edate=edate) - education_obj.save() - if 'profilesubmit' in request.POST: - about_me = request.POST.get('about') - age = request.POST.get('age') - address = request.POST.get('address') - contact = request.POST.get('contact') - pic = request.POST.get('pic') - # futu = request.POST.get('futu') - # print(studentplacement_obj.future_aspect) - # print('fut=', fut) - # print('futu=', futu) - # if studentplacement_obj.future_aspect == "HIGHER STUDIES": - # if futu == 2: - # studentplacement_obj.future_aspect = "PLACEMENT" - # elif studentplacement_obj.future_aspect == "PLACEMENT": - # if futu == None: - # studentplacement_obj.future_aspect = "HIGHER STUDIES" - extrainfo_obj = ExtraInfo.objects.get(user=user) - extrainfo_obj.about_me = about_me - extrainfo_obj.age = age - extrainfo_obj.address = address - extrainfo_obj.phone_no = contact - extrainfo_obj.profile_picture = pic - extrainfo_obj.save() - profile = get_object_or_404(ExtraInfo, Q(user=user)) - if 'skillsubmit' in request.POST: - form = AddSkill(request.POST) - if form.is_valid(): - skill = form.cleaned_data['skill'] - skill_rating = form.cleaned_data['skill_rating'] - has_obj = Has.objects.select_related('skill_id','unique_id').create(unique_id=student, - skill_id=Skill.objects.get(skill=skill), - skill_rating = skill_rating) - has_obj.save() - if 'achievementsubmit' in request.POST: - form = AddAchievement(request.POST) - if form.is_valid(): - achievement = form.cleaned_data['achievement'] - achievement_type = form.cleaned_data['achievement_type'] - description = form.cleaned_data['description'] - issuer = form.cleaned_data['issuer'] - date_earned = form.cleaned_data['date_earned'] - achievement_obj = Achievement.objects.select_related('unique_id').create(unique_id=student, - achievement=achievement, - achievement_type=achievement_type, - description=description, - issuer=issuer, - date_earned=date_earned) - achievement_obj.save() - if 'publicationsubmit' in request.POST: - form = AddPublication(request.POST) - if form.is_valid(): - publication_title = form.cleaned_data['publication_title'] - description = form.cleaned_data['description'] - publisher = form.cleaned_data['publisher'] - publication_date = form.cleaned_data['publication_date'] - publication_obj = Publication.objects.select_related('unique_id').create(unique_id=student, - publication_title= - publication_title, - publisher=publisher, - description=description, - publication_date=publication_date) - publication_obj.save() - if 'patentsubmit' in request.POST: - form = AddPatent(request.POST) - if form.is_valid(): - patent_name = form.cleaned_data['patent_name'] - description = form.cleaned_data['description'] - patent_office = form.cleaned_data['patent_office'] - patent_date = form.cleaned_data['patent_date'] - patent_obj = Patent.objects.select_related('unique_id').create(unique_id=student, patent_name=patent_name, - patent_office=patent_office, - description=description, - patent_date=patent_date) - patent_obj.save() - if 'coursesubmit' in request.POST: - form = AddCourse(request.POST) - if form.is_valid(): - course_name = form.cleaned_data['course_name'] - description = form.cleaned_data['description'] - license_no = form.cleaned_data['license_no'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - course_obj = Course.objects.select_related('unique_id').create(unique_id=student, course_name=course_name, - license_no=license_no, - description=description, - sdate=sdate, edate=edate) - course_obj.save() - if 'projectsubmit' in request.POST: - form = AddProject(request.POST) - if form.is_valid(): - project_name = form.cleaned_data['project_name'] - project_status = form.cleaned_data['project_status'] - summary = form.cleaned_data['summary'] - project_link = form.cleaned_data['project_link'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - project_obj = Project.objects.create(unique_id=student, summary=summary, - project_name=project_name, - project_status=project_status, - project_link=project_link, - sdate=sdate, edate=edate) - project_obj.save() - if 'experiencesubmit' in request.POST: - form = AddExperience(request.POST) - if form.is_valid(): - title = form.cleaned_data['title'] - status = form.cleaned_data['status'] - company = form.cleaned_data['company'] - location = form.cleaned_data['location'] - description = form.cleaned_data['description'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - experience_obj = Experience.objects.select_related('unique_id').create(unique_id=student, title=title, - company=company, location=location, - status=status, - description=description, - sdate=sdate, edate=edate) - experience_obj.save() - - if 'deleteskill' in request.POST: - hid = request.POST['deleteskill'] - hs = Has.objects.select_related('skill_id','unique_id').get(Q(pk=hid)) - hs.delete() - if 'deleteedu' in request.POST: - hid = request.POST['deleteedu'] - hs = Education.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletecourse' in request.POST: - hid = request.POST['deletecourse'] - hs = Course.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteexp' in request.POST: - hid = request.POST['deleteexp'] - hs = Experience.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepro' in request.POST: - hid = request.POST['deletepro'] - hs = Project.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteach' in request.POST: - hid = request.POST['deleteach'] - hs = Achievement.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepub' in request.POST: - hid = request.POST['deletepub'] - hs = Publication.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletepat' in request.POST: - hid = request.POST['deletepat'] - hs = Patent.objects.get(Q(pk=hid)) - hs.delete() - - placementschedule = PlacementSchedule.objects.select_related('notify_id').filter( - Q(placement_date__gte=date.today())).values_list('notify_id', flat=True) - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(unique_id=student, - notify_id__in=placementschedule)).order_by('-timestamp') - - - check_invitation_date(placementstatus) - - # facult and other staff view only statistics - if not (current or current1 or current2): - return redirect('/placement/statistics/') - - # delete the schedule - if 'deletesch' in request.POST: - delete_sch_key = request.POST['delete_sch_key'] - try: - placement_schedule = PlacementSchedule.objects.select_related('notify_id').get(pk = delete_sch_key) - NotifyStudent.objects.get(pk=placement_schedule.notify_id.id).delete() - placement_schedule.delete() - messages.success(request, 'Schedule Deleted Successfully') - except Exception as e: - messages.error(request, 'Problem Occurred for Schedule Delete!!!') - - # saving all the schedule details - if 'schedulesubmit' in request.POST: - form5 = AddSchedule(request.POST, request.FILES) - if form5.is_valid(): - company_name = form5.cleaned_data['company_name'] - placement_date = form5.cleaned_data['placement_date'] - location = form5.cleaned_data['location'] - ctc = form5.cleaned_data['ctc'] - time = form5.cleaned_data['time'] - attached_file = form5.cleaned_data['attached_file'] - placement_type = form5.cleaned_data['placement_type'] - role_offered = request.POST.get('role') - description = form5.cleaned_data['description'] - - try: - comp_name = CompanyDetails.objects.filter(company_name=company_name)[0] - except: - CompanyDetails.objects.create(company_name=company_name) - - try: - role = Role.objects.filter(role=role_offered)[0] - except: - role = Role.objects.create(role=role_offered) - role.save() - - - notify = NotifyStudent.objects.create(placement_type=placement_type, - company_name=company_name, - description=description, - ctc=ctc, - timestamp=timezone.now()) - - schedule = PlacementSchedule.objects.select_related('notify_id').create(notify_id=notify, - title=company_name, - description=description, - placement_date=placement_date, - attached_file = attached_file, - role=role, - location=location, time=time) - - notify.save() - schedule.save() - messages.success(request, "Schedule Added Successfull!!") - - - schedules = PlacementSchedule.objects.select_related('notify_id').all() - - - context = { - 'current': current, - 'current1': current1, - 'current2': current2, - 'schedule_tab': schedule_tab, - 'schedules': schedules, - 'placementstatus': placementstatus, - 'form5': form5, - } - - return render(request, 'placementModule/placement.html', context) - - - -def invite_status(request): - ''' - function to check the invitation status - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus_placement = [] - placementstatus_pbi = [] - mnplacement_tab = 1 - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - placement_get_request = False - pbi_get_request = False - - # invitation status for placement - if 'studentplacementsearchsubmit' in request.POST: - mnplacement_post = 1 - mnpbi_post = 0 - form = ManagePlacementRecord(request.POST) - - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - request.session['mn_stuname'] = stuname - request.session['mn_ctc'] = ctc - request.session['mn_cname'] = cname - request.session['mn_rollno'] = rollno - - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - # pagination stuff starts from here - total_query = placementstatus_placement.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - # when the request from pagination with some page number - if request.GET.get('placement_page') != None: - mnplacement_post = 1 - mnpbi_post = 0 - no_pagination = 1 - try: - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=request.session['mn_cname'], - ctc__gte=request.session['mn_ctc'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['mn_stuname'])), - id__icontains=request.session['mn_rollno'])) - ))))) - except: - placementstatus_placement = [] - - if placementstatus_placement != '': - total_query = placementstatus_placement.count() - else: - total_query = 0 - - if total_query > 30: - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('placement_page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - # invitation status for pbi - if 'studentpbisearchsubmit' in request.POST: - mnpbi_tab = 1 - mnpbi_post = 1 - mnplacement_post = 0 - form = ManagePbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - request.session['mn_pbi_stuname'] = stuname - request.session['mn_pbi_ctc'] = ctc - request.session['mn_pbi_cname'] = cname - request.session['mn_pbi_rollno'] = rollno - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - total_query = placementstatus_pbi.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - if request.GET.get('pbi_page') != None: - mnpbi_tab = 1 - mnpbi_post = 1 - no_pagination = 1 - try: - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=request.session['mn_pbi_cname'], - ctc__gte=request.session['mn_pbi_ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['mn_pbi_stuname'])), - id__icontains=request.session['mn_pbi_rollno'])) - ))))) - except: - placementstatus_pbi = '' - - if placementstatus_pbi != '': - total_query = placementstatus_pbi.count() - else: - total_query = 0 - if total_query > 30: - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - - if 'pdf_gen_invitation_status' in request.POST: - - placementstatus = None - if 'pdf_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'pdf_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - return render_to_pdf('placementModule/pdf_invitation_status.html', context) - - if 'excel_gen_invitation_status' in request.POST: - - placementstatus = None - if 'excel_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'excel_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - - years = PlacementRecord.objects.filter(~Q(placement_type="HIGHER STUDIES")).values('year').annotate(Count('year')) - records = PlacementRecord.objects.values('name', 'year', 'ctc', 'placement_type').annotate(Count('name'), Count('year'), Count('placement_type'), Count('ctc')) - - - return export_to_xls_invitation_status(placementstatus) - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'mnplacement_tab': mnplacement_tab, - 'placementstatus_placement': placementstatus_placement, - 'placementstatus_pbi': placementstatus_pbi, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - - - - - - - invitecheck=0 - for r in records: - r['name__count'] = 0 - r['year__count'] = 0 - r['placement_type__count'] = 0 - tcse = dict() - tece = dict() - tme = dict() - tadd = dict() - for y in years: - tcse[y['year']] = 0 - tece[y['year']] = 0 - tme[y['year']] = 0 - for r in records: - if r['year'] == y['year']: - if r['placement_type'] != "HIGHER STUDIES": - for z in studentrecord: - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "CSE": - tcse[y['year']] = tcse[y['year']]+1 - r['name__count'] = r['name__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ECE": - tece[y['year']] = tece[y['year']]+1 - r['year__count'] = r['year__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ME": - tme[y['year']] = tme[y['year']]+1 - r['placement_type__count'] = r['placement_type__count']+1 - tadd[y['year']] = tcse[y['year']]+tece[y['year']]+tme[y['year']] - y['year__count'] = [tadd[y['year']], tcse[y['year']], tece[y['year']], tme[y['year']]] - - form2 = SearchPlacementRecord(initial={}) - form3 = SearchPbiRecord(initial={}) - form4 = SearchHigherRecord(initial={}) - - - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - if len(current1)!=0 or len(current2)!=0: - delete_operation = 1 - if len(current) == 0: - current = None - pbirecord= '' - placementrecord= '' - higherrecord= '' - total_query=0 - total_query1 = 0 - total_query2= 0 - p="" - p1="" - p2="" - placement_search_record=" " - pbi_search_record=" " - higher_search_record=" " - # results of the searched query under placement tab - if 'studentplacementrecordsubmit' in request.POST: - officer_statistics_past = 1 - form = SearchPlacementRecord(request.POST) - if form.is_valid(): - - - - - print("IS VALID") - - - - #for student name - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except Exception as e: - print("Error") - print(e) - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - - - # for student CTC - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - - #for company name - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - - #for student roll - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - #for admission year - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - - - - - """placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name, - id__icontains=rollno)))))))) - #print("In if:", placementrecord) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)) - print("Agein p:",p) - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno))))))) - - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - print(p) - - - total_query = p.count() - - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - s = Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])) - - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except Exception as e: - print(e) - placementrecord = '' - - if placementrecord != '': - total_query = placementrecord.count() - else: - total_query = 0 - no_records=1 - print(placementrecord) - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - placementrecord = '' - - if total_query!=0: - placement_search_record=p - # results of the searched query under pbi tab - if 'studentpbirecordsubmit' in request.POST: - officer_statistics_past_pbi_search = 1 - form = SearchPbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - p1 = PlacementRecord.objects.filter( - Q(placement_type="PBI", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - """else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] -""" - total_query1 = p1.count() - - if total_query1 > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query1 > 30 and total_query1 <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=ctc, year=request.session['year'])), - unique_id__in=Student.objects.filter(( - Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter(Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except: - print('except') - pbirecord = '' - - if pbirecord != '': - total_query = pbirecord.count() - else: - total_query = 0 - - if total_query > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - pbirecord = '' - if total_query1!=0: - pbi_search_record=p1 - - # results of the searched query under higher studies tab - if 'studenthigherrecordsubmit' in request.POST: - officer_statistics_past_higher_search = 1 - form = SearchHigherRecord(request.POST) - if form.is_valid(): - # getting all the variables send through form - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['test_type']: - test_type = form.cleaned_data['test_type'] - else: - test_type = '' - if form.cleaned_data['uname']: - uname = form.cleaned_data['uname'] - else: - uname = '' - if form.cleaned_data['test_score']: - test_score = form.cleaned_data['test_score'] - else: - test_score = 0 - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - # result of the query when year is given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, year=year, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - - p2 = PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", name__icontains=stuname, year__icontains=year)) - - """else: - # result of the query when year is not given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['test_score'] = test_score - request.session['uname'] = uname - request.session['test_type'] = test_type - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - total_query2 = p2.count() - - if total_query2 > 30: - pagination_higher = 1 - paginator = Paginator(p2, 30) - page = request.GET.get('page', 1) - p2 = paginator.page(page) - page = int(page) - total_page = int(page+3) - - if page < (paginator.num_pages-3): - if total_query2 > 30 and total_query2 <= 60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(page-2, paginator.num_pages+1) - else: - pagination_higher = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - year=request.session['year'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - else: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - except: - higherrecord = '' - - if higherrecord != '': - total_query = higherrecord.count() - else: - total_query = 0 - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(higherrecord, 30) - page = request.GET.get('page', 1) - higherrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - higherrecord = '' - if total_query2!=0: - higher_search_record=p2 - - context = { - 'form2' : form2, - 'form3' : form3, - 'form4' : form4, - 'current' : current, - 'current1' : current1, - 'current2' : current2, - - - 'all_records': all_records, #for flashing all placement Schedule - - 'placement_search_record': placement_search_record, - 'pbi_search_record': pbi_search_record, - 'higher_search_record': higher_search_record, - - - - 'statistics_tab' : statistics_tab, - 'pbirecord' : pbirecord, - 'placementrecord' : placementrecord, - 'higherrecord' : higherrecord, - 'years' : years, - 'records' : records, - 'delete_operation' : delete_operation, - 'page_range': page_range, - 'paginator': paginator, - 'pagination_placement': pagination_placement, - 'pagination_pbi': pagination_pbi, - 'pagination_higher': pagination_higher, - 'is_disabled': is_disabled, - 'officer_statistics_past_pbi_search': officer_statistics_past_pbi_search, - 'officer_statistics_past_higher_search': officer_statistics_past_higher_search - } - - return render(request, 'placementModule/placementstatistics.html', context) - - - -def get_reference_list(request): - if request.method == 'POST': - - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - student = get_object_or_404(Student, Q(id=profile.id)) - print(student) - reference_objects = Reference.select_related('unique_id').objects.filter(unique_id=student) - reference_objects = serializers.serialize('json', list(reference_objects)) - - context = { - 'reference_objs': reference_objects - } - return JsonResponse(context) - - -# Ajax for the company name dropdown for CompanyName when filling AddSchedule -def company_name_dropdown(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - company_names = CompanyDetails.objects.filter(Q(company_name__startswith=current_value)) - company_name = [] - for name in company_names: - company_name.append(name.company_name) - - context = { - 'company_names': company_name - } - - return JsonResponse(context) - - -# Ajax for all the roles in the dropdown -def checking_roles(request): - if request.method == 'POST': - current_value = request.POST.get('current_value') - all_roles = Role.objects.filter(Q(role__startswith=current_value)) - role_name = [] - for role in all_roles: - role_name.append(role.role) - return JsonResponse({'all_roles': role_name}) - -@login_required -def Placement__Schedule(request): - ''' - function include the functionality of first tab of UI - for student, placement officer & placement chairman - - placement officer & placement chairman - - can add schedule - - can delete schedule - student - - accepted or declined schedule - - ''' - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - schedule_tab = 1 - placementstatus = '' - - - form5 = AddSchedule(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - # If the user is Student - if current: - student = get_object_or_404(Student, Q(id=profile.id)) - - # Student view for showing accepted or declined schedule - if request.method == 'POST': - if 'studentapprovesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - pk=request.POST['studentapprovesubmit']).update( - invitation='ACCEPTED', - timestamp=timezone.now()) - if 'studentdeclinesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(pk=request.POST['studentdeclinesubmit'])).update( - invitation='REJECTED', - timestamp=timezone.now()) - - if 'educationsubmit' in request.POST: - form = AddEducation(request.POST) - if form.is_valid(): - institute = form.cleaned_data['institute'] - degree = form.cleaned_data['degree'] - grade = form.cleaned_data['grade'] - stream = form.cleaned_data['stream'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - education_obj = Education.objects.select_related('unique_id').create( - unique_id=student, degree=degree, - grade=grade, institute=institute, - stream=stream, sdate=sdate, edate=edate) - education_obj.save() - if 'profilesubmit' in request.POST: - about_me = request.POST.get('about') - age = request.POST.get('age') - address = request.POST.get('address') - contact = request.POST.get('contact') - pic = request.POST.get('pic') - # futu = request.POST.get('futu') - # print(studentplacement_obj.future_aspect) - # print('fut=', fut) - # print('futu=', futu) - # if studentplacement_obj.future_aspect == "HIGHER STUDIES": - # if futu == 2: - # studentplacement_obj.future_aspect = "PLACEMENT" - # elif studentplacement_obj.future_aspect == "PLACEMENT": - # if futu == None: - # studentplacement_obj.future_aspect = "HIGHER STUDIES" - extrainfo_obj = ExtraInfo.objects.get(user=user) - extrainfo_obj.about_me = about_me - extrainfo_obj.age = age - extrainfo_obj.address = address - extrainfo_obj.phone_no = contact - extrainfo_obj.profile_picture = pic - extrainfo_obj.save() - profile = get_object_or_404(ExtraInfo, Q(user=user)) - if 'skillsubmit' in request.POST: - form = AddSkill(request.POST) - if form.is_valid(): - skill = form.cleaned_data['skill'] - skill_rating = form.cleaned_data['skill_rating'] - has_obj = Has.objects.select_related('skill_id','unique_id').create(unique_id=student, - skill_id=Skill.objects.get(skill=skill), - skill_rating = skill_rating) - has_obj.save() - if 'achievementsubmit' in request.POST: - form = AddAchievement(request.POST) - if form.is_valid(): - achievement = form.cleaned_data['achievement'] - achievement_type = form.cleaned_data['achievement_type'] - description = form.cleaned_data['description'] - issuer = form.cleaned_data['issuer'] - date_earned = form.cleaned_data['date_earned'] - achievement_obj = Achievement.objects.select_related('unique_id').create(unique_id=student, - achievement=achievement, - achievement_type=achievement_type, - description=description, - issuer=issuer, - date_earned=date_earned) - achievement_obj.save() - if 'publicationsubmit' in request.POST: - form = AddPublication(request.POST) - if form.is_valid(): - publication_title = form.cleaned_data['publication_title'] - description = form.cleaned_data['description'] - publisher = form.cleaned_data['publisher'] - publication_date = form.cleaned_data['publication_date'] - publication_obj = Publication.objects.select_related('unique_id').create(unique_id=student, - publication_title= - publication_title, - publisher=publisher, - description=description, - publication_date=publication_date) - publication_obj.save() - if 'patentsubmit' in request.POST: - form = AddPatent(request.POST) - if form.is_valid(): - patent_name = form.cleaned_data['patent_name'] - description = form.cleaned_data['description'] - patent_office = form.cleaned_data['patent_office'] - patent_date = form.cleaned_data['patent_date'] - patent_obj = Patent.objects.select_related('unique_id').create(unique_id=student, patent_name=patent_name, - patent_office=patent_office, - description=description, - patent_date=patent_date) - patent_obj.save() - if 'coursesubmit' in request.POST: - form = AddCourse(request.POST) - if form.is_valid(): - course_name = form.cleaned_data['course_name'] - description = form.cleaned_data['description'] - license_no = form.cleaned_data['license_no'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - course_obj = Course.objects.select_related('unique_id').create(unique_id=student, course_name=course_name, - license_no=license_no, - description=description, - sdate=sdate, edate=edate) - course_obj.save() - if 'projectsubmit' in request.POST: - form = AddProject(request.POST) - if form.is_valid(): - project_name = form.cleaned_data['project_name'] - project_status = form.cleaned_data['project_status'] - summary = form.cleaned_data['summary'] - project_link = form.cleaned_data['project_link'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - project_obj = Project.objects.create(unique_id=student, summary=summary, - project_name=project_name, - project_status=project_status, - project_link=project_link, - sdate=sdate, edate=edate) - project_obj.save() - if 'experiencesubmit' in request.POST: - form = AddExperience(request.POST) - if form.is_valid(): - title = form.cleaned_data['title'] - status = form.cleaned_data['status'] - company = form.cleaned_data['company'] - location = form.cleaned_data['location'] - description = form.cleaned_data['description'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - experience_obj = Experience.objects.select_related('unique_id').create(unique_id=student, title=title, - company=company, location=location, - status=status, - description=description, - sdate=sdate, edate=edate) - experience_obj.save() - - if 'deleteskill' in request.POST: - hid = request.POST['deleteskill'] - hs = Has.objects.select_related('skill_id','unique_id').get(Q(pk=hid)) - hs.delete() - if 'deleteedu' in request.POST: - hid = request.POST['deleteedu'] - hs = Education.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletecourse' in request.POST: - hid = request.POST['deletecourse'] - hs = Course.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteexp' in request.POST: - hid = request.POST['deleteexp'] - hs = Experience.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepro' in request.POST: - hid = request.POST['deletepro'] - hs = Project.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteach' in request.POST: - hid = request.POST['deleteach'] - hs = Achievement.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepub' in request.POST: - hid = request.POST['deletepub'] - hs = Publication.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletepat' in request.POST: - hid = request.POST['deletepat'] - hs = Patent.objects.get(Q(pk=hid)) - hs.delete() - - placementschedule = PlacementSchedule.objects.select_related('notify_id').filter( - Q(placement_date__gte=date.today())).values_list('notify_id', flat=True) - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(unique_id=student, - notify_id__in=placementschedule)).order_by('-timestamp') - - - check_invitation_date(placementstatus) - - # facult and other staff view only statistics - if not (current or current1 or current2): - return redirect('/placement/statistics/') - - # delete the schedule - if 'deletesch' in request.POST: - delete_sch_key = request.POST['delete_sch_key'] - try: - placement_schedule = PlacementSchedule.objects.select_related('notify_id').get(pk = delete_sch_key) - NotifyStudent.objects.get(pk=placement_schedule.notify_id.id).delete() - placement_schedule.delete() - messages.success(request, 'Schedule Deleted Successfully') - except Exception as e: - messages.error(request, 'Problem Occurred for Schedule Delete!!!') - - # saving all the schedule details - if 'schedulesubmit' in request.POST: - form5 = AddSchedule(request.POST, request.FILES) - if form5.is_valid(): - company_name = form5.cleaned_data['company_name'] - placement_date = form5.cleaned_data['placement_date'] - location = form5.cleaned_data['location'] - ctc = form5.cleaned_data['ctc'] - time = form5.cleaned_data['time'] - attached_file = form5.cleaned_data['attached_file'] - placement_type = form5.cleaned_data['placement_type'] - role_offered = request.POST.get('role') - description = form5.cleaned_data['description'] - - try: - comp_name = CompanyDetails.objects.filter(company_name=company_name)[0] - except: - CompanyDetails.objects.create(company_name=company_name) - - try: - role = Role.objects.filter(role=role_offered)[0] - except: - role = Role.objects.create(role=role_offered) - role.save() - - - notify = NotifyStudent.objects.create(placement_type=placement_type, - company_name=company_name, - description=description, - ctc=ctc, - timestamp=timezone.now()) - - schedule = PlacementSchedule.objects.select_related('notify_id').create(notify_id=notify, - title=company_name, - description=description, - placement_date=placement_date, - attached_file = attached_file, - role=role, - location=location, time=time) - - notify.save() - schedule.save() - messages.success(request, "Schedule Added Successfull!!") - - - schedules = PlacementSchedule.objects.select_related('notify_id').all() - - - context = { - 'current': current, - 'current1': current1, - 'current2': current2, - 'schedule_tab': schedule_tab, - 'schedules': schedules, - 'placementstatus': placementstatus, - 'form5': form5, - } - - return render(request, 'placementModule/placement.html', context) - - - -def invite_status(request): - ''' - function to check the invitation status - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus_placement = [] - placementstatus_pbi = [] - mnplacement_tab = 1 - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - placement_get_request = False - pbi_get_request = False - - # invitation status for placement - if 'studentplacementsearchsubmit' in request.POST: - mnplacement_post = 1 - mnpbi_post = 0 - form = ManagePlacementRecord(request.POST) - - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - request.session['mn_stuname'] = stuname - request.session['mn_ctc'] = ctc - request.session['mn_cname'] = cname - request.session['mn_rollno'] = rollno - - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - # pagination stuff starts from here - total_query = placementstatus_placement.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - # when the request from pagination with some page number - if request.GET.get('placement_page') != None: - mnplacement_post = 1 - mnpbi_post = 0 - no_pagination = 1 - try: - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=request.session['mn_cname'], - ctc__gte=request.session['mn_ctc'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['mn_stuname'])), - id__icontains=request.session['mn_rollno'])) - ))))) - except: - placementstatus_placement = [] - - if placementstatus_placement != '': - total_query = placementstatus_placement.count() - else: - total_query = 0 - - if total_query > 30: - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('placement_page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - # invitation status for pbi - if 'studentpbisearchsubmit' in request.POST: - mnpbi_tab = 1 - mnpbi_post = 1 - mnplacement_post = 0 - form = ManagePbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - request.session['mn_pbi_stuname'] = stuname - request.session['mn_pbi_ctc'] = ctc - request.session['mn_pbi_cname'] = cname - request.session['mn_pbi_rollno'] = rollno - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - total_query = placementstatus_pbi.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - if request.GET.get('pbi_page') != None: - mnpbi_tab = 1 - mnpbi_post = 1 - no_pagination = 1 - try: - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=request.session['mn_pbi_cname'], - ctc__gte=request.session['mn_pbi_ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['mn_pbi_stuname'])), - id__icontains=request.session['mn_pbi_rollno'])) - ))))) - except: - placementstatus_pbi = '' - - if placementstatus_pbi != '': - total_query = placementstatus_pbi.count() - else: - total_query = 0 - if total_query > 30: - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - - if 'pdf_gen_invitation_status' in request.POST: - - placementstatus = None - if 'pdf_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'pdf_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - return render_to_pdf('placementModule/pdf_invitation_status.html', context) - - if 'excel_gen_invitation_status' in request.POST: - - placementstatus = None - if 'excel_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'excel_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - - return export_to_xls_invitation_status(placementstatus) - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'mnplacement_tab': mnplacement_tab, - 'placementstatus_placement': placementstatus_placement, - 'placementstatus_pbi': placementstatus_pbi, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - - -@login_required -def placement(request): - ''' - function include the functionality of first tab of UI - for student, placement officer & placement chairman - - placement officer & placement chairman - - can add schedule - - can delete schedule - student - - accepted or declined schedule - - ''' - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - schedule_tab = 1 - placementstatus = '' - - - form5 = AddSchedule(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - print(current) - - # If the user is Student - if current: - student = get_object_or_404(Student, Q(id=profile.id)) - - # Student view for showing accepted or declined schedule - if request.method == 'POST': - if 'studentapprovesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - pk=request.POST['studentapprovesubmit']).update( - invitation='ACCEPTED', - timestamp=timezone.now()) - if 'studentdeclinesubmit' in request.POST: - status = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(pk=request.POST['studentdeclinesubmit'])).update( - invitation='REJECTED', - timestamp=timezone.now()) - - if 'educationsubmit' in request.POST: - form = AddEducation(request.POST) - if form.is_valid(): - institute = form.cleaned_data['institute'] - degree = form.cleaned_data['degree'] - grade = form.cleaned_data['grade'] - stream = form.cleaned_data['stream'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - education_obj = Education.objects.select_related('unique_id').create( - unique_id=student, degree=degree, - grade=grade, institute=institute, - stream=stream, sdate=sdate, edate=edate) - education_obj.save() - if 'profilesubmit' in request.POST: - about_me = request.POST.get('about') - age = request.POST.get('age') - address = request.POST.get('address') - contact = request.POST.get('contact') - pic = request.POST.get('pic') - - extrainfo_obj = ExtraInfo.objects.get(user=user) - extrainfo_obj.about_me = about_me - extrainfo_obj.age = age - extrainfo_obj.address = address - extrainfo_obj.phone_no = contact - extrainfo_obj.profile_picture = pic - extrainfo_obj.save() - profile = get_object_or_404(ExtraInfo, Q(user=user)) - if 'skillsubmit' in request.POST: - form = AddSkill(request.POST) - if form.is_valid(): - skill = form.cleaned_data['skill'] - skill_rating = form.cleaned_data['skill_rating'] - has_obj = Has.objects.select_related('skill_id','unique_id').create(unique_id=student, - skill_id=Skill.objects.get(skill=skill), - skill_rating = skill_rating) - has_obj.save() - if 'achievementsubmit' in request.POST: - form = AddAchievement(request.POST) - if form.is_valid(): - achievement = form.cleaned_data['achievement'] - achievement_type = form.cleaned_data['achievement_type'] - description = form.cleaned_data['description'] - issuer = form.cleaned_data['issuer'] - date_earned = form.cleaned_data['date_earned'] - achievement_obj = Achievement.objects.select_related('unique_id').create(unique_id=student, - achievement=achievement, - achievement_type=achievement_type, - description=description, - issuer=issuer, - date_earned=date_earned) - achievement_obj.save() - if 'publicationsubmit' in request.POST: - form = AddPublication(request.POST) - if form.is_valid(): - publication_title = form.cleaned_data['publication_title'] - description = form.cleaned_data['description'] - publisher = form.cleaned_data['publisher'] - publication_date = form.cleaned_data['publication_date'] - publication_obj = Publication.objects.select_related('unique_id').create(unique_id=student, - publication_title= - publication_title, - publisher=publisher, - description=description, - publication_date=publication_date) - publication_obj.save() - if 'patentsubmit' in request.POST: - form = AddPatent(request.POST) - if form.is_valid(): - patent_name = form.cleaned_data['patent_name'] - description = form.cleaned_data['description'] - patent_office = form.cleaned_data['patent_office'] - patent_date = form.cleaned_data['patent_date'] - patent_obj = Patent.objects.select_related('unique_id').create(unique_id=student, patent_name=patent_name, - patent_office=patent_office, - description=description, - patent_date=patent_date) - patent_obj.save() - if 'coursesubmit' in request.POST: - form = AddCourse(request.POST) - if form.is_valid(): - course_name = form.cleaned_data['course_name'] - description = form.cleaned_data['description'] - license_no = form.cleaned_data['license_no'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - course_obj = Course.objects.select_related('unique_id').create(unique_id=student, course_name=course_name, - license_no=license_no, - description=description, - sdate=sdate, edate=edate) - course_obj.save() - if 'projectsubmit' in request.POST: - form = AddProject(request.POST) - if form.is_valid(): - project_name = form.cleaned_data['project_name'] - project_status = form.cleaned_data['project_status'] - summary = form.cleaned_data['summary'] - project_link = form.cleaned_data['project_link'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - project_obj = Project.objects.create(unique_id=student, summary=summary, - project_name=project_name, - project_status=project_status, - project_link=project_link, - sdate=sdate, edate=edate) - project_obj.save() - if 'experiencesubmit' in request.POST: - form = AddExperience(request.POST) - if form.is_valid(): - title = form.cleaned_data['title'] - status = form.cleaned_data['status'] - company = form.cleaned_data['company'] - location = form.cleaned_data['location'] - description = form.cleaned_data['description'] - sdate = form.cleaned_data['sdate'] - edate = form.cleaned_data['edate'] - experience_obj = Experience.objects.select_related('unique_id').create(unique_id=student, title=title, - company=company, location=location, - status=status, - description=description, - sdate=sdate, edate=edate) - experience_obj.save() - - if 'deleteskill' in request.POST: - hid = request.POST['deleteskill'] - hs = Has.objects.select_related('skill_id','unique_id').get(Q(pk=hid)) - hs.delete() - if 'deleteedu' in request.POST: - hid = request.POST['deleteedu'] - hs = Education.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletecourse' in request.POST: - hid = request.POST['deletecourse'] - hs = Course.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteexp' in request.POST: - hid = request.POST['deleteexp'] - hs = Experience.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepro' in request.POST: - hid = request.POST['deletepro'] - hs = Project.objects.get(Q(pk=hid)) - hs.delete() - if 'deleteach' in request.POST: - hid = request.POST['deleteach'] - hs = Achievement.objects.get(Q(pk=hid)) - hs.delete() - if 'deletepub' in request.POST: - hid = request.POST['deletepub'] - hs = Publication.objects.select_related('unique_id').get(Q(pk=hid)) - hs.delete() - if 'deletepat' in request.POST: - hid = request.POST['deletepat'] - hs = Patent.objects.get(Q(pk=hid)) - hs.delete() - - placementschedule = PlacementSchedule.objects.select_related('notify_id').filter( - Q(placement_date__gte=date.today())).values_list('notify_id', flat=True) - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(unique_id=student, - notify_id__in=placementschedule)).order_by('-timestamp') - - - check_invitation_date(placementstatus) - - # facult and other staff view only statistics - if not (current or current1 or current2): - return redirect('/placement/statistics/') - - # delete the schedule - if 'deletesch' in request.POST: - delete_sch_key = request.POST['delete_sch_key'] - try: - placement_schedule = PlacementSchedule.objects.select_related('notify_id').get(pk = delete_sch_key) - NotifyStudent.objects.get(pk=placement_schedule.notify_id.id).delete() - placement_schedule.delete() - messages.success(request, 'Schedule Deleted Successfully') - except Exception as e: - messages.error(request, 'Problem Occurred for Schedule Delete!!!') - - # saving all the schedule details - if 'schedulesubmit' in request.POST: - form5 = AddSchedule(request.POST, request.FILES) - if form5.is_valid(): - company_name = form5.cleaned_data['company_name'] - placement_date = form5.cleaned_data['placement_date'] - location = form5.cleaned_data['location'] - ctc = form5.cleaned_data['ctc'] - time = form5.cleaned_data['time'] - attached_file = form5.cleaned_data['attached_file'] - placement_type = form5.cleaned_data['placement_type'] - role_offered = request.POST.get('role') - description = form5.cleaned_data['description'] - - try: - comp_name = CompanyDetails.objects.filter(company_name=company_name)[0] - except: - CompanyDetails.objects.create(company_name=company_name) - - try: - role = Role.objects.filter(role=role_offered)[0] - except: - role = Role.objects.create(role=role_offered) - role.save() - - - notify = NotifyStudent.objects.create(placement_type=placement_type, - company_name=company_name, - description=description, - ctc=ctc, - timestamp=timezone.now()) - - schedule = PlacementSchedule.objects.select_related('notify_id').create(notify_id=notify, - title=company_name, - description=description, - placement_date=placement_date, - attached_file = attached_file, - role=role, - location=location, time=time) - - notify.save() - schedule.save() - messages.success(request, "Schedule Added Successfull!!") - - - schedules = PlacementSchedule.objects.select_related('notify_id').all() - - - context = { - 'current': current, - 'current1': current1, - 'current2': current2, - 'schedule_tab': schedule_tab, - 'schedules': schedules, - 'placementstatus': placementstatus, - 'form5': form5, - } - - return render(request, 'placementModule/placement.html', context) - - -@login_required -def delete_invitation_status(request): - ''' - function to delete the invitation that has been sent to the students - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus = [] - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - - if 'deleteinvitationstatus' in request.POST: - delete_invit_status_key = request.POST['deleteinvitationstatus'] - - try: - PlacementStatus.objects.select_related('unique_id','notify_id').get(pk=delete_invit_status_key).delete() - messages.success(request, 'Invitation Deleted Successfully') - except Exception as e: - logger.error(e) - - if 'pbi_tab_active' in request.POST: - mnpbi_tab = 1 - else: - mnplacement_tab = 1 - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'placementstatus': placementstatus, - # 'current':current, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - -def invitation_status(request): - ''' - function to check the invitation status - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus_placement = [] - placementstatus_pbi = [] - mnplacement_tab = 1 - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - placement_get_request = False - pbi_get_request = False - - # invitation status for placement - if 'studentplacementsearchsubmit' in request.POST: - mnplacement_post = 1 - mnpbi_post = 0 - form = ManagePlacementRecord(request.POST) - - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - request.session['mn_stuname'] = stuname - request.session['mn_ctc'] = ctc - request.session['mn_cname'] = cname - request.session['mn_rollno'] = rollno - - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - # pagination stuff starts from here - total_query = placementstatus_placement.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - # when the request from pagination with some page number - if request.GET.get('placement_page') != None: - mnplacement_post = 1 - mnpbi_post = 0 - no_pagination = 1 - try: - placementstatus_placement = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=request.session['mn_cname'], - ctc__gte=request.session['mn_ctc'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['mn_stuname'])), - id__icontains=request.session['mn_rollno'])) - ))))) - except: - placementstatus_placement = [] - - if placementstatus_placement != '': - total_query = placementstatus_placement.count() - else: - total_query = 0 - - if total_query > 30: - paginator = Paginator(placementstatus_placement, 30) - page = request.GET.get('placement_page', 1) - placementstatus_placement = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - # invitation status for pbi - if 'studentpbisearchsubmit' in request.POST: - mnpbi_tab = 1 - mnpbi_post = 1 - mnplacement_post = 0 - form = ManagePbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['company']: - cname = form.cleaned_data['company'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - request.session['mn_pbi_stuname'] = stuname - request.session['mn_pbi_ctc'] = ctc - request.session['mn_pbi_cname'] = cname - request.session['mn_pbi_rollno'] = rollno - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - total_query = placementstatus_pbi.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - if request.GET.get('pbi_page') != None: - mnpbi_tab = 1 - mnpbi_post = 1 - no_pagination = 1 - try: - placementstatus_pbi = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=request.session['mn_pbi_cname'], - ctc__gte=request.session['mn_pbi_ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['mn_pbi_stuname'])), - id__icontains=request.session['mn_pbi_rollno'])) - ))))) - except: - placementstatus_pbi = '' - - if placementstatus_pbi != '': - total_query = placementstatus_pbi.count() - else: - total_query = 0 - if total_query > 30: - paginator = Paginator(placementstatus_pbi, 30) - page = request.GET.get('pbi_page', 1) - placementstatus_pbi = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - - - if 'pdf_gen_invitation_status' in request.POST: - - placementstatus = None - if 'pdf_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'pdf_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - return render_to_pdf('placementModule/pdf_invitation_status.html', context) - - if 'excel_gen_invitation_status' in request.POST: - - placementstatus = None - if 'excel_gen_invitation_status_placement' in request.POST: - stuname = request.session['mn_stuname'] - ctc = request.session['mn_ctc'] - cname = request.session['mn_cname'] - rollno = request.session['mn_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter(Q(notify_id__in=NotifyStudent.objects.filter - (Q(placement_type="PLACEMENT", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - - if 'excel_gen_invitation_status_pbi' in request.POST: - stuname = request.session['mn_pbi_stuname'] - ctc = request.session['mn_pbi_ctc'] - cname = request.session['mn_pbi_cname'] - rollno = request.session['mn_pbi_rollno'] - - placementstatus = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - Q(notify_id__in=NotifyStudent.objects.filter( - Q(placement_type="PBI", - company_name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=stuname)), - id__icontains=rollno))))))).order_by('id') - - context = { - 'placementstatus' : placementstatus - } - - - return export_to_xls_invitation_status(placementstatus) - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'mnplacement_tab': mnplacement_tab, - 'placementstatus_placement': placementstatus_placement, - 'placementstatus_pbi': placementstatus_pbi, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - -@login_required -def student_records(request): - ''' - function for searching the records of student - ''' - if request.user.is_staff==True: - user = request.user - strecord_tab = 1 - no_pagination = 0 - is_disabled = 0 - paginator = '' - page_range = '' - mnplacement_tab = 1 - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - # querying the students details a/c to the input data - if 'recordsubmit' in request.POST: - student_record_check = 1 - form1 = SearchStudentRecord(request.POST) - if form1.is_valid(): - if form1.cleaned_data['name']: - name = form1.cleaned_data['name'] - else: - name = '' - if form1.cleaned_data['rollno']: - rollno = form1.cleaned_data['rollno'] - else: - rollno = '' - - programme = form1.cleaned_data['programme'] - - department = [] - if form1.cleaned_data['dep_btech']: - department.extend(form1.cleaned_data['dep_btech']) - if form1.cleaned_data['dep_mtech']: - department.extend(form1.cleaned_data['dep_mtech']) - if form1.cleaned_data['dep_bdes']: - department.extend(form1.cleaned_data['dep_bdes']) - if form1.cleaned_data['dep_mdes']: - department.extend(form1.cleaned_data['dep_mdes']) - if form1.cleaned_data['dep_phd']: - department.extend(form1.cleaned_data['dep_phd']) - - if form1.cleaned_data['cpi']: - cpi = form1.cleaned_data['cpi'] - else: - cpi = 0 - debar = form1.cleaned_data['debar'] - placed_type = form1.cleaned_data['placed_type'] - - request.session['name'] = name - request.session['rollno'] = rollno - request.session['programme'] = programme - request.session['department'] = department - request.session['cpi'] = str(cpi) - request.session['debar'] = debar - request.session['placed_type'] = placed_type - - - students = Student.objects.filter( - Q(id__in=ExtraInfo.objects.filter(Q( - user__in=User.objects.filter(Q(first_name__icontains=name)), - department__in=DepartmentInfo.objects.filter(Q(name__in=department)), - id__icontains=rollno)), - programme=programme, - cpi__gte=cpi)).filter(Q(pk__in=StudentPlacement.objects.filter( - Q(debar=debar, placed_type=placed_type)).values('unique_id_id'))).order_by('id') - - # pagination stuff starts from here - st = students - student_record_check= 1 - total_query = students.count() - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(students, 30) - page = request.GET.get('page', 1) - students = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - # when the request came from pagintion with some page no. - if request.GET.get('page') != None: - try: - students = Student.objects.filter( - Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['name']) - ), - department__in=DepartmentInfo.objects.filter( - Q(name__in=request.session['department']) - ), - id__icontains=request.session['rollno'] - ) - ), - programme=request.session['programme'], - cpi__gte=decimal.Decimal(request.session['cpi']))).filter(Q(pk__in=StudentPlacement.objects.filter(Q(debar=request.session['debar'], - placed_type=request.session['placed_type'])).values('unique_id_id'))).order_by('id') - except: - students = '' - - if students != '': - total_query = students.count() - else: - total_query = 0 - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(students, 30) - page = request.GET.get('page', 1) - students = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - students = '' - - if 'debar' in request.POST: - spid = request.POST['debar'] - sr = StudentPlacement.objects.get(Q(pk=spid)) - sr.debar = "DEBAR" - sr.save() - if 'undebar' in request.POST: - spid = request.POST['undebar'] - sr = StudentPlacement.objects.get(Q(pk=spid)) - sr.debar = "NOT DEBAR" - sr.save() - - # pdf generation logic - if 'pdf_gen_std_record' in request.POST: - - name = request.session['name'] - rollno = request.session['rollno'] - programme = request.session['programme'] - department = request.session['department'] - cpi = int(request.session['cpi']) - debar = request.session['debar'] - placed_type = request.session['placed_type'] - - students = Student.objects.filter( - Q(id__in=ExtraInfo.objects.filter(Q( - user__in=User.objects.filter(Q(first_name__icontains=name)), - department__in=DepartmentInfo.objects.filter(Q(name__in=department)), - id__icontains=rollno)), - programme=programme, - cpi__gte=cpi)).filter(Q(pk__in=StudentPlacement.objects.filter( - Q(debar=debar, placed_type=placed_type)).values('unique_id_id'))).order_by('id') - - context = { - 'students' : students - } - - - return render_to_pdf('placementModule/pdf_student_record.html', context) - - # excel generation logic - if 'excel_gen_std_record' in request.POST: - - name = request.session['name'] - rollno = request.session['rollno'] - programme = request.session['programme'] - department = request.session['department'] - cpi = int(request.session['cpi']) - debar = request.session['debar'] - placed_type = request.session['placed_type'] - - students = Student.objects.filter( - Q(id__in=ExtraInfo.objects.filter(Q( - user__in=User.objects.filter(Q(first_name__icontains=name)), - department__in=DepartmentInfo.objects.filter(Q(name__in=department)), - id__icontains=rollno)), - programme=programme, - cpi__gte=cpi)).filter(Q(pk__in=StudentPlacement.objects.filter( - Q(debar=debar, placed_type=placed_type)).values('unique_id_id'))).order_by('id') - - context = { - 'students' : students - } - - - return export_to_xls_std_records(students) - - - # for sending the invite to students for particular schedule - if 'sendinvite' in request.POST: - # invitecheck=1; - - form13 = SendInvite(request.POST) - - if form13.is_valid(): - if form13.cleaned_data['company']: - if form13.cleaned_data['rollno']: - rollno = form13.cleaned_data['rollno'] - else: - rollno = '' - - programme = form13.cleaned_data['programme'] - - department = [] - if form13.cleaned_data['dep_btech']: - department.extend(form13.cleaned_data['dep_btech']) - if form13.cleaned_data['dep_mtech']: - department.extend(form13.cleaned_data['dep_mtech']) - if form13.cleaned_data['dep_bdes']: - department.extend(form13.cleaned_data['dep_bdes']) - if form13.cleaned_data['dep_mdes']: - department.extend(form13.cleaned_data['dep_mdes']) - if form13.cleaned_data['dep_phd']: - department.extend(form13.cleaned_data['dep_phd']) - - - if form13.cleaned_data['cpi']: - cpi = form13.cleaned_data['cpi'] - else: - cpi = 0 - - if form13.cleaned_data['no_of_days']: - no_of_days = form13.cleaned_data['no_of_days'] - else: - no_of_days = 10 - - - comp = form13.cleaned_data['company'] - - notify = NotifyStudent.objects.get(company_name=comp.company_name, - placement_type=comp.placement_type) - - students = Student.objects.filter( - Q( - id__in = ExtraInfo.objects.filter( - Q( - department__in = DepartmentInfo.objects.filter(Q(name__in=department)), - id__icontains = rollno - ) - ), - programme = programme, - cpi__gte = cpi - ) - ).exclude(id__in = PlacementStatus.objects.select_related('unique_id','notify_id').filter( - notify_id=notify).values_list('unique_id', flat=True)) - - PlacementStatus.objects.bulk_create( [PlacementStatus(notify_id=notify, - unique_id=student, no_of_days=no_of_days) for student in students] ) - - for st in students: - placement_cell_notif(request.user, st.id.user, "") - - students = '' - messages.success(request, 'Notification Sent') - else: - messages.error(request, 'Problem Occurred!! Please Try Again!!') - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'current1': current1, - 'current2': current2, - 'mnplacement_tab': mnplacement_tab, - 'strecord_tab': strecord_tab, - 'students': students, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - return redirect('/placement') - - -@login_required -def manage_records(request): - ''' - function to manage the records - - can add the records under placement | pbi | higher studies - - can also search the records under placement | pbi | higher studies - ''' - user = request.user - mnrecord_tab = 1 - pagination_placement = 0 - pagination_pbi = 0 - pagination_higher = 0 - is_disabled = 0 - years = None - records = None - paginator = '' - page_range = '' - pbirecord = None - placementrecord = None - higherrecord = None - officer_statistics_past_pbi_search = 0 - officer_statistics_past_higher_search = 0 - - profile = get_object_or_404(ExtraInfo, Q(user=user)) - studentrecord = StudentRecord.objects.all() - - years = PlacementRecord.objects.filter(~Q(placement_type="HIGHER STUDIES")).values('year').annotate(Count('year')) - records = PlacementRecord.objects.values('name', 'year', 'ctc', 'placement_type').annotate(Count('name'), Count('year'), Count('placement_type'), Count('ctc')) - - - form2 = SearchPlacementRecord(initial={}) - form3 = SearchPbiRecord(initial={}) - form4 = SearchHigherRecord(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - - if len(current) == 0: - current = None - - - try: - # for adding the new data for student under higher studies category - if 'studenthigheraddsubmit' in request.POST: - officer_statistics_past_higher_add = 1 - form = SearchHigherRecord(request.POST) - if form.is_valid(): - rollno = form.cleaned_data['roll'] - uname = form.cleaned_data['uname'] - test_score = form.cleaned_data['test_score'] - test_type = form.cleaned_data['test_type'] - year = form.cleaned_data['year'] - placementr = PlacementRecord.objects.create(year=year, name=uname, - placement_type="HIGHER STUDIES", - test_type=test_type, - test_score=test_score) - studentr = StudentRecord.objects.select_related('unique_id','record_id').create(record_id=placementr, - unique_id=Student.objects.get - ((Q(id=ExtraInfo.objects.get - (Q(id=rollno)))))) - studentr.save() - placementr.save() - messages.success(request, 'Record Added Successfully!!') - - # for adding the new data for student under pbi category - if 'studentpbiaddsubmit' in request.POST: - officer_statistics_past_pbi_add = 1 - form = SearchPbiRecord(request.POST) - if form.is_valid(): - rollno = form.cleaned_data['roll'] - ctc = form.cleaned_data['ctc'] - year = form.cleaned_data['year'] - cname = form.cleaned_data['cname'] - placementr = PlacementRecord.objects.create(year=year, ctc=ctc, - placement_type="PBI", - name=cname) - studentr = StudentRecord.objects.select_related('unique_id','record_id').create(record_id=placementr, - unique_id=Student.objects.get - ((Q(id=ExtraInfo.objects.get - (Q(id=rollno)))))) - studentr.save() - placementr.save() - messages.success(request, 'Record Added Successfully!!') - - # for adding the new data for student under placement category - if 'studentplacementaddsubmit' in request.POST: - officer_statistics_past_add = 1 - form = SearchPlacementRecord(request.POST) - if form.is_valid(): - rollno = form.cleaned_data['roll'] - ctc = form.cleaned_data['ctc'] - year = form.cleaned_data['year'] - cname = form.cleaned_data['cname'] - placementr = PlacementRecord.objects.create(year=year, ctc=ctc, - placement_type="PLACEMENT", - name=cname) - studentr = StudentRecord.objects.select_related('unique_id','record_id').create(record_id=placementr, - unique_id=Student.objects.get - ((Q(id=ExtraInfo.objects.get - (Q(id=rollno)))))) - studentr.save() - placementr.save() - messages.success(request, 'Record Added Successfully!!') - - # for searching the student details under placement category - if 'studentplacementrecordsubmit' in request.POST: - officer_statistics_past = 1 - form = SearchPlacementRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc, year=year)) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc, year=year)), unique_id__in=Student.objects.filter((Q(id__in=ExtraInfo.objects.filter(Q(user__in=User.objects.filter(Q(first_name__icontains=stuname)),id__icontains=rollno))))))) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", name__icontains=cname, ctc__gte=ctc)), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter(Q(first_name__icontains=stuname)), - id__icontains=rollno))))))) - - request.session['stuname'] = stuname - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] - - total_query = placementrecord.count() - - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - s = Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno']))))))) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno']))))))) - except: - placementrecord = '' - - if placementrecord != '': - total_query = placementrecord.count() - else: - total_query = 0 - - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - placementrecord = '' - - # for searching the student details under pbi category - if 'studentpbirecordsubmit' in request.POST: - officer_statistics_past_pbi_search = 1 - form = SearchPbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - request.session['stuname'] = stuname - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] - - total_query = pbirecord.count() - - if total_query > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=ctc, year=request.session['year'])), - unique_id__in=Student.objects.filter(( - Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno']))))))) - else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter(Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno']))))))) - except: - print('except') - pbirecord = '' - - if pbirecord != '': - total_query = pbirecord.count() - else: - total_query = 0 - - if total_query > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - pbirecord = '' - - # for searching the student details under higher studies category - if 'studenthigherrecordsubmit' in request.POST: - officer_statistics_past_higher_search = 1 - form = SearchHigherRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - else: - stuname = '' - if form.cleaned_data['test_type']: - test_type = form.cleaned_data['test_type'] - else: - test_type = '' - if form.cleaned_data['uname']: - uname = form.cleaned_data['uname'] - else: - uname = '' - if form.cleaned_data['test_score']: - test_score = form.cleaned_data['test_score'] - else: - test_score = 0 - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, year=year, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - else: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=stuname)), - id__icontains=rollno)) - ))))) - request.session['stuname'] = stuname - request.session['test_score'] = test_score - request.session['uname'] = uname - request.session['test_type'] = test_type - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] - - total_query = higherrecord.count() - - if total_query > 30: - pagination_higher = 1 - paginator = Paginator(higherrecord, 30) - page = request.GET.get('page', 1) - higherrecord = paginator.page(page) - page = int(page) - total_page = int(page+3) - - if page < (paginator.num_pages-3): - if total_query > 30 and total_query <= 60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(page-2, paginator.num_pages+1) - else: - pagination_higher = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - year=request.session['year'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno'])) - ))))) - else: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['stuname'])), - id__icontains=request.session['rollno'])) - ))))) - except: - print('except') - higherrecord = '' - - if higherrecord != '': - total_query = higherrecord.count() - else: - total_query = 0 - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(higherrecord, 30) - page = request.GET.get('page', 1) - higherrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - higherrecord = '' - - - except Exception as e: - messages.error(request, "Problem Occurred!!! Please Try Again with Correct Info!!") - print(e) - - - context = { - 'form2' : form2, - 'form3' : form3, - 'form4' : form4, - 'current' : current, - 'current1' : current1, - 'current2' : current2, - 'mnrecord_tab' : mnrecord_tab, - 'pbirecord' : pbirecord, - 'placementrecord' : placementrecord, - 'higherrecord' : higherrecord, - 'years' : years, - 'records' : records, - 'page_range': page_range, - 'paginator': paginator, - 'pagination_placement': pagination_placement, - 'pagination_pbi': pagination_pbi, - 'pagination_higher': pagination_higher, - 'is_disabled': is_disabled, - 'officer_statistics_past_pbi_search': officer_statistics_past_pbi_search, - 'officer_statistics_past_higher_search': officer_statistics_past_higher_search - } - - return render(request, 'placementModule/managerecords.html', context) - - - -@login_required -def delete_invite_status(request): - ''' - function to delete the invitation that has been sent to the students - ''' - user = request.user - strecord_tab = 1 - mnpbi_tab = 0 - mnplacement_post = 0 - mnpbi_post = 0 - invitation_status_tab = 1 - placementstatus = [] - - no_pagination = 1 - is_disabled = 0 - paginator = '' - page_range = '' - - if 'deleteinvitationstatus' in request.POST: - delete_invit_status_key = request.POST['deleteinvitationstatus'] - - try: - PlacementStatus.objects.select_related('unique_id','notify_id').get(pk=delete_invit_status_key).delete() - messages.success(request, 'Invitation Deleted Successfully') - except Exception as e: - logger.error(e) - - if 'pbi_tab_active' in request.POST: - mnpbi_tab = 1 - else: - mnplacement_tab = 1 - - form1 = SearchStudentRecord(initial={}) - form9 = ManagePbiRecord(initial={}) - form11 = ManagePlacementRecord(initial={}) - form13 = SendInvite(initial={}) - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - - context = { - 'form1': form1, - 'form9': form9, - 'form11': form11, - 'form13': form13, - 'invitation_status_tab': invitation_status_tab, - 'mnplacement_post': mnplacement_post, - 'mnpbi_tab': mnpbi_tab, - 'placementstatus': placementstatus, - # 'current':current, - 'current1': current1, - 'current2': current2, - 'strecord_tab': strecord_tab, - 'mnpbi_post': mnpbi_post, - 'page_range': page_range, - 'paginator': paginator, - 'no_pagination': no_pagination, - 'is_disabled': is_disabled, - } - - return render(request, 'placementModule/studentrecords.html', context) - - - -@login_required -def placement_statistics(request): - ''' - logic of the view shown under Placement Statistics tab - ''' - user = request.user - - statistics_tab = 1 - strecord_tab=1 - delete_operation = 0 - pagination_placement = 0 - pagination_pbi = 0 - pagination_higher = 0 - is_disabled = 0 - paginator = '' - page_range = '' - officer_statistics_past_pbi_search = 0 - officer_statistics_past_higher_search = 0 - - profile = get_object_or_404(ExtraInfo, Q(user=user)) - studentrecord = StudentRecord.objects.select_related('unique_id','record_id').all() - - years = PlacementRecord.objects.filter(~Q(placement_type="HIGHER STUDIES")).values('year').annotate(Count('year')) - records = PlacementRecord.objects.values('name', 'year', 'ctc', 'placement_type').annotate(Count('name'), Count('year'), Count('placement_type'), Count('ctc')) - - - - - #working here to fetch all placement record - all_records=PlacementRecord.objects.all() - print(all_records) - - - - - - - invitecheck=0 - for r in records: - r['name__count'] = 0 - r['year__count'] = 0 - r['placement_type__count'] = 0 - tcse = dict() - tece = dict() - tme = dict() - tadd = dict() - for y in years: - tcse[y['year']] = 0 - tece[y['year']] = 0 - tme[y['year']] = 0 - for r in records: - if r['year'] == y['year']: - if r['placement_type'] != "HIGHER STUDIES": - for z in studentrecord: - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "CSE": - tcse[y['year']] = tcse[y['year']]+1 - r['name__count'] = r['name__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ECE": - tece[y['year']] = tece[y['year']]+1 - r['year__count'] = r['year__count']+1 - if z.record_id.name == r['name'] and z.record_id.year == r['year'] and z.unique_id.id.department.name == "ME": - tme[y['year']] = tme[y['year']]+1 - r['placement_type__count'] = r['placement_type__count']+1 - tadd[y['year']] = tcse[y['year']]+tece[y['year']]+tme[y['year']] - y['year__count'] = [tadd[y['year']], tcse[y['year']], tece[y['year']], tme[y['year']]] - - form2 = SearchPlacementRecord(initial={}) - form3 = SearchPbiRecord(initial={}) - form4 = SearchHigherRecord(initial={}) - - - current1 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement chairman")) - current2 = HoldsDesignation.objects.filter(Q(working=user, designation__name="placement officer")) - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - - if len(current1)!=0 or len(current2)!=0: - delete_operation = 1 - if len(current) == 0: - current = None - pbirecord= '' - placementrecord= '' - higherrecord= '' - total_query=0 - total_query1 = 0 - total_query2= 0 - p="" - p1="" - p2="" - placement_search_record=" " - pbi_search_record=" " - higher_search_record=" " - # results of the searched query under placement tab - if 'studentplacementrecordsubmit' in request.POST: - officer_statistics_past = 1 - form = SearchPlacementRecord(request.POST) - if form.is_valid(): - - - - - print("IS VALID") - - - - #for student name - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except Exception as e: - print("Error") - print(e) - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - - - # for student CTC - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - - #for company name - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - - #for student roll - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - - #for admission year - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - first_name__icontains=first_name, - last_name__icontains=last_name), - id__icontains=rollno)) - ))) - - p = PlacementRecord.objects.filter(Q(placement_type="PLACEMENT",name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - - print(p) - - - total_query = p.count() - - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - s = Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])) - - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'], - year=request.session['year'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - s = Student.objects.filter((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))) - - p = PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])) - - placementrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PLACEMENT", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except Exception as e: - print(e) - placementrecord = '' - - if placementrecord != '': - total_query = placementrecord.count() - else: - total_query = 0 - no_records=1 - print(placementrecord) - if total_query > 30: - pagination_placement = 1 - paginator = Paginator(placementrecord, 30) - page = request.GET.get('page', 1) - placementrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_placement = 0 - else: - placementrecord = '' - - if total_query!=0: - placement_search_record=p - # results of the searched query under pbi tab - if 'studentpbirecordsubmit' in request.POST: - officer_statistics_past_pbi_search = 1 - form = SearchPbiRecord(request.POST) - if form.is_valid(): - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['ctc']: - ctc = form.cleaned_data['ctc'] - else: - ctc = 0 - if form.cleaned_data['cname']: - cname = form.cleaned_data['cname'] - else: - cname = '' - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc, year=year)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - p1 = PlacementRecord.objects.filter( - Q(placement_type="PBI", name__icontains=stuname, ctc__icontains=ctc, year__icontains=year)) - """else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="PBI", - name__icontains=cname, - ctc__gte=ctc)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['ctc'] = ctc - request.session['cname'] = cname - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year'] -""" - total_query1 = p1.count() - - if total_query1 > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query1 > 30 and total_query1 <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=ctc, year=request.session['year'])), - unique_id__in=Student.objects.filter(( - Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - else: - pbirecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter(Q(placement_type="PBI", - name__icontains=request.session['cname'], - ctc__gte=request.session['ctc'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno']))))))) - except: - print('except') - pbirecord = '' - - if pbirecord != '': - total_query = pbirecord.count() - else: - total_query = 0 - - if total_query > 30: - pagination_pbi = 1 - paginator = Paginator(pbirecord, 30) - page = request.GET.get('page', 1) - pbirecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - pagination_pbi = 0 - else: - pbirecord = '' - if total_query1!=0: - pbi_search_record=p1 - - # results of the searched query under higher studies tab - if 'studenthigherrecordsubmit' in request.POST: - officer_statistics_past_higher_search = 1 - form = SearchHigherRecord(request.POST) - if form.is_valid(): - # getting all the variables send through form - if form.cleaned_data['stuname']: - stuname = form.cleaned_data['stuname'] - try: - first_name = stuname.split(" ")[0] - last_name = stuname.split(" ")[1] - except: - first_name = stuname - last_name = '' - else: - stuname = '' - first_name = '' - last_name = '' - if form.cleaned_data['test_type']: - test_type = form.cleaned_data['test_type'] - else: - test_type = '' - if form.cleaned_data['uname']: - uname = form.cleaned_data['uname'] - else: - uname = '' - if form.cleaned_data['test_score']: - test_score = form.cleaned_data['test_score'] - else: - test_score = 0 - if form.cleaned_data['roll']: - rollno = form.cleaned_data['roll'] - else: - rollno = '' - if form.cleaned_data['year']: - year = form.cleaned_data['year'] - # result of the query when year is given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter(Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, year=year, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - - p2 = PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", name__icontains=stuname, year__icontains=year)) - - """else: - # result of the query when year is not given - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter - (Q(placement_type="HIGHER STUDIES", - test_type__icontains=test_type, - name__icontains=uname, - test_score__gte=test_score)), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter - (Q(user__in=User.objects.filter - (Q(first_name__icontains=first_name, - last_name__icontains=last_name)), - id__icontains=rollno)) - ))))) - request.session['first_name'] = first_name - request.session['last_name'] = last_name - request.session['test_score'] = test_score - request.session['uname'] = uname - request.session['test_type'] = test_type - request.session['rollno'] = rollno - request.session['year'] = form.cleaned_data['year']""" - - total_query2 = p2.count() - - if total_query2 > 30: - pagination_higher = 1 - paginator = Paginator(p2, 30) - page = request.GET.get('page', 1) - p2 = paginator.page(page) - page = int(page) - total_page = int(page+3) - - if page < (paginator.num_pages-3): - if total_query2 > 30 and total_query2 <= 60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(page-2, paginator.num_pages+1) - else: - pagination_higher = 0 - else: - if request.GET.get('page') != None: - try: - if request.session['year']: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - year=request.session['year'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter( - (Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - else: - higherrecord = StudentRecord.objects.select_related('unique_id','record_id').filter( - Q(record_id__in=PlacementRecord.objects.filter( - Q(placement_type="HIGHER STUDIES", - test_type__icontains=request.session['test_type'], - name__icontains=request.session['uname'], - test_score__gte=request.session['test_score'])), - unique_id__in=Student.objects.filter - ((Q(id__in=ExtraInfo.objects.filter( - Q(user__in=User.objects.filter( - Q(first_name__icontains=request.session['first_name'], - last_name__icontains=request.session['last_name'])), - id__icontains=request.session['rollno'])) - ))))) - except: - higherrecord = '' - - if higherrecord != '': - total_query = higherrecord.count() - else: - total_query = 0 - - if total_query > 30: - no_pagination = 1 - paginator = Paginator(higherrecord, 30) - page = request.GET.get('page', 1) - higherrecord = paginator.page(page) - page = int(page) - total_page = int(page + 3) - - if page<(paginator.num_pages-3): - if total_query > 30 and total_query <=60: - page_range = range(1, 3) - else: - page_range = range(1, total_page+1) - - if page >= 5: - is_disabled = 1 - page_range = range(page-2, total_page) - else: - if page >= 5: - is_disabled = 1 - page_range = range(page-2, paginator.num_pages+1) - else: - page_range = range(1, paginator.num_pages+1) - else: - no_pagination = 0 - else: - higherrecord = '' - if total_query2!=0: - higher_search_record=p2 - - context = { - 'form2' : form2, - 'form3' : form3, - 'form4' : form4, - 'current' : current, - 'current1' : current1, - 'current2' : current2, - - - 'all_records': all_records, #for flashing all placement Schedule - - 'placement_search_record': placement_search_record, - 'pbi_search_record': pbi_search_record, - 'higher_search_record': higher_search_record, - - - - 'statistics_tab' : statistics_tab, - 'pbirecord' : pbirecord, - 'placementrecord' : placementrecord, - 'higherrecord' : higherrecord, - 'years' : years, - 'records' : records, - 'delete_operation' : delete_operation, - 'page_range': page_range, - 'paginator': paginator, - 'pagination_placement': pagination_placement, - 'pagination_pbi': pagination_pbi, - 'pagination_higher': pagination_higher, - 'is_disabled': is_disabled, - 'officer_statistics_past_pbi_search': officer_statistics_past_pbi_search, - 'officer_statistics_past_higher_search': officer_statistics_past_higher_search - } - - return render(request, 'placementModule/placementstatistics.html', context) - - -@login_required -def delete_placement_statistics(request): - """ - The function is used to delete the placement statistic record. - @param: - request - trivial - @variables: - record_id = stores current StudentRecord Id. - """ - if 'deleterecord' in request.POST or 'deleterecordmanaged' in request.POST: - try: - if 'deleterecord' in request.POST: - record_id = int(request.POST['deleterecord']) - elif 'deleterecordmanaged' in request.POST: - record_id = int(request.POST['deleterecordmanaged']) - - student_record = StudentRecord.objects.get(pk=record_id) - PlacementRecord.objects.get(id=student_record.record_id.id).delete() - student_record.delete() - messages.success(request, 'Placement Statistics deleted Successfully!!') - - except Exception as e: - messages.error(request, 'Problem Occurred!! Please Try Again!!') - print(e) - - - if 'deleterecordmanaged' in request.POST: - return redirect('/placement/manage_records/') - - return redirect('/placement/statistics/') - - -def cv(request, username): - # Retrieve data or whatever you need - """ - The function is used to generate the cv in the pdf format. - Embeds the data into the predefined template. - @param: - request - trivial - username - name of user whose cv is to be generated - @variables: - user = stores current user - profile = stores extrainfo of user - current = Stores all working students from HoldsDesignation for the respective degignation - achievementcheck = variable for achievementcheck in form for cv generation - educationcheck = variable for educationcheck in form for cv generation - publicationcheck = variable for publicationcheck in form for cv generation - patentcheck = variable for patentcheck in form for cv generation - internshipcheck = variable for internshipcheck in form for cv generation - projectcheck = variable for projectcheck in form for cv generation - coursecheck = variable for coursecheck in form for cv generation - skillcheck = variable for skillcheck in form for cv generation - user = get_object_or_404(User, Q(username=username)) - profile = get_object_or_404(ExtraInfo, Q(user=user)) - import datetime - now = stores current timestamp - roll = roll of the user - student = variable storing the profile data - studentplacement = variable storing the placement data - skills = variable storing the skills data - education = variable storing the education data - course = variable storing the course data - experience = variable storing the experience data - project = variable storing the project data - achievement = variable storing the achievement data - publication = variable storing the publication data - patent = variable storing the patent data - """ - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - if current: - if request.method == 'POST': - achievementcheck = request.POST.get('achievementcheck') - educationcheck = request.POST.get('educationcheck') - publicationcheck = request.POST.get('publicationcheck') - patentcheck = request.POST.get('patentcheck') - internshipcheck = request.POST.get('internshipcheck') - projectcheck = request.POST.get('projectcheck') - coursecheck = request.POST.get('coursecheck') - skillcheck = request.POST.get('skillcheck') - reference_list = request.POST.getlist('reference_checkbox_list') - extracurricularcheck = request.POST.get('extracurricularcheck') - conferencecheck = request.POST.get('conferencecheck') - else: - conferencecheck = '1' - achievementcheck = '1' - educationcheck = '1' - publicationcheck = '1' - patentcheck = '1' - internshipcheck = '1' - projectcheck = '1' - coursecheck = '1' - skillcheck = '1' - extracurricularcheck = '1' - - - - user = get_object_or_404(User, Q(username=username)) - profile = get_object_or_404(ExtraInfo, Q(user=user)) - student_info=get_object_or_404(Student,Q(id=user.username)) - - batch=student_info.batch - - now = datetime.datetime.now() - print("year----->",now.year) - if now.year-batch<=4: - roll=now.year-batch - else: - roll=4 - - - student = get_object_or_404(Student, Q(id=profile.id)) - skills = Has.objects.select_related('skill_id','unique_id').filter(Q(unique_id=student)) - education = Education.objects.select_related('unique_id').filter(Q(unique_id=student)) - reference = Reference.objects.filter(id__in=reference_list) - course = Course.objects.select_related('unique_id').filter(Q(unique_id=student)) - experience = Experience.objects.select_related('unique_id').filter(Q(unique_id=student)) - project = Project.objects.select_related('unique_id').filter(Q(unique_id=student)) - achievement = Achievement.objects.select_related('unique_id').filter(Q(unique_id=student)) - extracurricular = Extracurricular.objects.select_related('unique_id').filter(Q(unique_id=student)) - conference = Conference.objects.select_related('unique_id').filter(Q(unique_id=student)) - publication = Publication.objects.select_related('unique_id').filter(Q(unique_id=student)) - patent = Patent.objects.select_related('unique_id').filter(Q(unique_id=student)) - today = datetime.date.today() - - if len(reference) == 0: - referencecheck = '0' - else: - referencecheck = '1' - - return render_to_pdf('placementModule/cv.html', {'pagesize': 'A4', 'user': user, 'references': reference, - 'profile': profile, 'projects': project, - 'skills': skills, 'educations': education, - 'courses': course, 'experiences': experience, - 'referencecheck': referencecheck, - 'achievements': achievement, - 'extracurriculars': extracurricular, - 'publications': publication, - 'patents': patent, 'roll': roll, - 'achievementcheck': achievementcheck, - 'extracurricularcheck': extracurricularcheck, - 'educationcheck': educationcheck, - 'publicationcheck': publicationcheck, - 'patentcheck': patentcheck, - 'conferencecheck': conferencecheck, - 'conferences': conference, - 'internshipcheck': internshipcheck, - 'projectcheck': projectcheck, - 'coursecheck': coursecheck, - 'skillcheck': skillcheck, - 'today':today}) - - -def render_to_pdf(template_src, context_dict): - """ - The function is used to generate the cv in the pdf format. - Embeds the data into the predefined template. - @param: - template_src - template of cv to be rendered - context_dict - data fetched from the dtatabase to be filled in the cv template - @variables: - template - stores the template - html - html rendered pdf - result - variable to store data in BytesIO - pdf - storing encoded html of pdf version - """ - template = get_template(template_src) - html = template.render(context_dict) - result = BytesIO() - pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) - if not pdf.err: - return HttpResponse(result.getvalue(), content_type='application/pdf') - return HttpResponse('We had some errors
%s
' % escape(html)) - - -def export_to_xls_std_records(qs): - """ - The function is used to generate the file in the xls format. - Embeds the data into the file. - """ - response = HttpResponse(content_type='application/ms-excel') - response['Content-Disposition'] = 'attachment; filename="report.xls"' - - wb = xlwt.Workbook(encoding='utf-8') - ws = wb.add_sheet('Report') - - row_num = 0 - - font_style = xlwt.XFStyle() - font_style.font.bold = True - - columns = ['Roll No.', 'Name', 'CPI', 'Department', 'Discipline', 'Placed', 'Debarred' ] - - for col_num in range(len(columns)): - ws.write(row_num, col_num, columns[col_num], font_style) - - font_style = xlwt.XFStyle() - - for student in qs: - row_num += 1 - - row = [] - row.append(student.id.id) - row.append(student.id.user.first_name+' '+student.id.user.last_name) - row.append(student.cpi) - row.append(student.programme) - row.append(student.id.department.name) - if student.studentplacement.placed_type == "PLACED": - row.append('Yes') - else: - row.append('No') - if student.studentplacement.placed_type == "DEBAR": - row.append('Yes') - else: - row.append('No') - - for col_num in range(len(row)): - ws.write(row_num, col_num, row[col_num], font_style) - - wb.save(response) - return response -def resume(request, username): - # Retrieve data or whatever you need - """ - The function is used to generate the cv in the pdf format. - Embeds the data into the predefined template. - @param: - request - trivial - username - name of user whose cv is to be generated - @variables: - user = stores current user - profile = stores extrainfo of user - current = Stores all working students from HoldsDesignation for the respective degignation - achievementcheck = variable for achievementcheck in form for cv generation - educationcheck = variable for educationcheck in form for cv generation - publicationcheck = variable for publicationcheck in form for cv generation - patentcheck = variable for patentcheck in form for cv generation - internshipcheck = variable for internshipcheck in form for cv generation - projectcheck = variable for projectcheck in form for cv generation - coursecheck = variable for coursecheck in form for cv generation - skillcheck = variable for skillcheck in form for cv generation - user = get_object_or_404(User, Q(username=username)) - profile = get_object_or_404(ExtraInfo, Q(user=user)) - import datetime - now = stores current timestamp - roll = roll of the user - student = variable storing the profile data - studentplacement = variable storing the placement data - skills = variable storing the skills data - education = variable storing the education data - course = variable storing the course data - experience = variable storing the experience data - project = variable storing the project data - achievement = variable storing the achievement data - publication = variable storing the publication data - patent = variable storing the patent data - """ - user = request.user - profile = get_object_or_404(ExtraInfo, Q(user=user)) - - current = HoldsDesignation.objects.filter(Q(working=user, designation__name="student")) - if current: - if request.method == 'POST': - achievementcheck = request.POST.get('achievementcheck') - educationcheck = request.POST.get('educationcheck') - publicationcheck = request.POST.get('publicationcheck') - patentcheck = request.POST.get('patentcheck') - internshipcheck = request.POST.get('internshipcheck') - projectcheck = request.POST.get('projectcheck') - coursecheck = request.POST.get('coursecheck') - skillcheck = request.POST.get('skillcheck') - reference_list = request.POST.getlist('reference_checkbox_list') - extracurricularcheck = request.POST.get('extracurricularcheck') - conferencecheck = request.POST.get('conferencecheck') - else: - conferencecheck = '1' - achievementcheck = '1' - educationcheck = '1' - publicationcheck = '1' - patentcheck = '1' - internshipcheck = '1' - projectcheck = '1' - coursecheck = '1' - skillcheck = '1' - extracurricularcheck = '1' - - - # print(achievementcheck,' ',educationcheck,' ',publicationcheck,' ',patentcheck,' ',internshipcheck,' ',projectcheck,' \n\n\n') - user = get_object_or_404(User, Q(username=username)) - profile = get_object_or_404(ExtraInfo, Q(user=user)) - now = datetime.datetime.now() - if int(str(profile.id)[:2]) == 20: - if (now.month>4): - roll = 1+now.year-int(str(profile.id)[:4]) - else: - roll = now.year-int(str(profile.id)[:4]) - else: - if (now.month>4): - roll = 1+(now.year)-int("20"+str(profile.id)[0:2]) - else: - roll = (now.year)-int("20"+str(profile.id)[0:2]) - - student = get_object_or_404(Student, Q(id=profile.id)) - skills = Has.objects.select_related('skill_id','unique_id').filter(Q(unique_id=student)) - education = Education.objects.select_related('unique_id').filter(Q(unique_id=student)) - reference = Reference.objects.filter(id__in=reference_list) - course = Course.objects.select_related('unique_id').filter(Q(unique_id=student)) - experience = Experience.objects.select_related('unique_id').filter(Q(unique_id=student)) - project = Project.objects.select_related('unique_id').filter(Q(unique_id=student)) - achievement = Achievement.objects.select_related('unique_id').filter(Q(unique_id=student)) - extracurricular = Extracurricular.objects.select_related('unique_id').filter(Q(unique_id=student)) - conference = Conference.objects.select_related('unique_id').filter(Q(unique_id=student)) - publication = Publication.objects.select_related('unique_id').filter(Q(unique_id=student)) - patent = Patent.objects.select_related('unique_id').filter(Q(unique_id=student)) - today = datetime.date.today() - - if len(reference) == 0: - referencecheck = '0' - else: - referencecheck = '1' - - return render_to_pdf('placementModule/cv.html', {'pagesize': 'A4', 'user': user, 'references': reference, - 'profile': profile, 'projects': project, - 'skills': skills, 'educations': education, - 'courses': course, 'experiences': experience, - 'referencecheck': referencecheck, - 'achievements': achievement, - 'extracurriculars': extracurricular, - 'publications': publication, - 'patents': patent, 'roll': roll, - 'achievementcheck': achievementcheck, - 'extracurricularcheck': extracurricularcheck, - 'educationcheck': educationcheck, - 'publicationcheck': publicationcheck, - 'patentcheck': patentcheck, - 'conferencecheck': conferencecheck, - 'conferences': conference, - 'internshipcheck': internshipcheck, - 'projectcheck': projectcheck, - 'coursecheck': coursecheck, - 'skillcheck': skillcheck, - 'today':today}) - - - -def export_to_xls_invitation_status(qs): - response = HttpResponse(content_type='application/ms-excel') - response['Content-Disposition'] = 'attachment; filename="report.xls"' - - wb = xlwt.Workbook(encoding='utf-8') - ws = wb.add_sheet('Report') - - - row_num = 0 - - font_style = xlwt.XFStyle() - font_style.font.bold = True - - columns = ['Roll No.', 'Name', 'Company', 'CTC', 'Invitation Status'] - - for col_num in range(len(columns)): - ws.write(row_num, col_num, columns[col_num], font_style) - - - font_style = xlwt.XFStyle() - - for student in qs: - row_num += 1 - - row = [] - row.append(student.unique_id.id.id) - row.append(student.unique_id.id.user.first_name+' '+student.unique_id.id.user.last_name) - row.append(student.notify_id.company_name) - row.append(student.notify_id.ctc) - row.append(student.invitation) - - for col_num in range(len(row)): - ws.write(row_num, col_num, row[col_num], font_style) - - wb.save(response) - return response - - -def check_invitation_date(placementstatus): - """ - The function is used to run before render of student placement view for ensuring that - last date for RESPONSE is not passed - @param: - placementstatus - queryset containing placement status of particular student - @variables: - ps - individual PlacementStatus object - """ - try: - for ps in placementstatus: - if ps.invitation=='PENDING': - dt = ps.timestamp+datetime.timedelta(days=ps.no_of_days) - if dt