From 46cea5e4d4824e4797d7b7da5eed77b9c3f72cc0 Mon Sep 17 00:00:00 2001 From: "K.Charan Teja Reddy" <129493881+Charan2437@users.noreply.github.com> Date: Mon, 3 Feb 2025 22:31:15 +0530 Subject: [PATCH 1/9] All changes of Complaint Management --- .../applications/complaint_system/api/urls.py | 2 +- .../complaint_system/api/views.py | 7 +- .../complaint_system/serializers.py | 90 + .../applications/complaint_system/urls.py | 113 +- .../applications/complaint_system/views.py | 2611 ++++++----------- 5 files changed, 986 insertions(+), 1837 deletions(-) create mode 100644 FusionIIIT/applications/complaint_system/serializers.py diff --git a/FusionIIIT/applications/complaint_system/api/urls.py b/FusionIIIT/applications/complaint_system/api/urls.py index 480cd9af7..5d7cacd0b 100644 --- a/FusionIIIT/applications/complaint_system/api/urls.py +++ b/FusionIIIT/applications/complaint_system/api/urls.py @@ -26,4 +26,4 @@ url(r'^removesupervisor/(?P[0-9]+)',views.edit_supervisor_api,name='supervisor-delete-api'), url(r'^updatesupervisor/(?P[0-9]+)',views.edit_supervisor_api,name='supervisor-put-api'), -] +] \ No newline at end of file diff --git a/FusionIIIT/applications/complaint_system/api/views.py b/FusionIIIT/applications/complaint_system/api/views.py index 304697017..c12b73ddb 100644 --- a/FusionIIIT/applications/complaint_system/api/views.py +++ b/FusionIIIT/applications/complaint_system/api/views.py @@ -23,7 +23,7 @@ def complaint_details_api(request,detailcomp_id1): if complaint_detail.worker_id is None: worker_detail_serialized = {} else : - worker_detail = Workers.objects.get(id=complaint_detail.worker_id.id) + worker_detail = worker_detail.objects.get(id=complaint_detail.worker_id) worker_detail_serialized = serializers.WorkersSerializers(instance=worker_detail).data complainer = User.objects.get(username=complaint_detail.complainer.user.username) complainer_serialized = serializers.UserSerializers(instance=complainer).data @@ -154,7 +154,7 @@ def caretaker_api(request): user = get_object_or_404(User ,username=request.user.username) user = ExtraInfo.objects.all().filter(user = user).first() try : - supervisor = Supervisor.objects.get(sup_id=user) + supervisor = Supervisor.objects.get(staff_id=user) except Supervisor.DoesNotExist: return Response({'message':'Logged in user does not have the permissions'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) serializer = serializers.CaretakerSerializers(data=request.data) @@ -170,7 +170,7 @@ def edit_caretaker_api(request,c_id): user = get_object_or_404(User ,username=request.user.username) user = ExtraInfo.objects.all().filter(user = user).first() try : - supervisor = Supervisor.objects.get(sup_id=user) + supervisor = Supervisor.objects.get(staff_id=user) except Supervisor.DoesNotExist: return Response({'message':'Logged in user does not have the permissions'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) try: @@ -230,4 +230,3 @@ def edit_supervisor_api(request,s_id): serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) - diff --git a/FusionIIIT/applications/complaint_system/serializers.py b/FusionIIIT/applications/complaint_system/serializers.py new file mode 100644 index 000000000..d224dcaf3 --- /dev/null +++ b/FusionIIIT/applications/complaint_system/serializers.py @@ -0,0 +1,90 @@ +from rest_framework import serializers +from .models import StudentComplain, Caretaker +from applications.globals.models import ExtraInfo + +# Added StudentComplainSerializer +class StudentComplainSerializer(serializers.ModelSerializer): + class Meta: + model = StudentComplain + fields = "__all__" + +# Added CaretakerSerializer +class CaretakerSerializer(serializers.ModelSerializer): + class Meta: + model = Caretaker + fields = "__all__" + +# Optionally, add ExtraInfoSerializer if needed +class ExtraInfoSerializer(serializers.ModelSerializer): + class Meta: + model = ExtraInfo + fields = "__all__" +from rest_framework import serializers +from .models import StudentComplain, Caretaker +from applications.globals.models import ExtraInfo + +# Serializer for StudentComplain (already added previously) +class StudentComplainSerializer(serializers.ModelSerializer): + class Meta: + model = StudentComplain + fields = '__all__' + +# Serializer for Caretaker (already added previously) +class CaretakerSerializer(serializers.ModelSerializer): + class Meta: + model = Caretaker + fields = '__all__' + +# Serializer for Feedback submission +class FeedbackSerializer(serializers.Serializer): + feedback = serializers.CharField() + rating = serializers.IntegerField() + +# Serializer for Resolve Pending complaints +class ResolvePendingSerializer(serializers.Serializer): + yesorno = serializers.ChoiceField(choices=[('Yes', 'Yes'), ('No', 'No')]) + comment = serializers.CharField(required=False) +# serializers.py + +from rest_framework import serializers +from .models import StudentComplain, Caretaker +from applications.globals.models import ExtraInfo + +# Serializer for StudentComplain (already added previously) +class StudentComplainSerializer(serializers.ModelSerializer): + class Meta: + model = StudentComplain + fields = '__all__' + +# Serializer for Caretaker (already added previously) +class CaretakerSerializer(serializers.ModelSerializer): + class Meta: + model = Caretaker + fields = '__all__' + +# Serializer for Feedback submission +class FeedbackSerializer(serializers.Serializer): + feedback = serializers.CharField() + rating = serializers.IntegerField() + +# Serializer for Resolve Pending complaints +class ResolvePendingSerializer(serializers.Serializer): + yesorno = serializers.ChoiceField(choices=[('Yes', 'Yes'), ('No', 'No')]) + comment = serializers.CharField(required=False, allow_blank=True) +# serializers.py + +from rest_framework import serializers +from .models import StudentComplain, Caretaker, Workers +from applications.globals.models import ExtraInfo + +# Serializer for StudentComplain (already added previously) +class StudentComplainSerializer(serializers.ModelSerializer): + class Meta: + model = StudentComplain + fields = '__all__' + +# Serializer for Workers (added to handle Workers model) +class WorkersSerializer(serializers.ModelSerializer): + class Meta: + model = Workers + fields = '__all__' diff --git a/FusionIIIT/applications/complaint_system/urls.py b/FusionIIIT/applications/complaint_system/urls.py index 2bd0c87e0..c39a5d965 100644 --- a/FusionIIIT/applications/complaint_system/urls.py +++ b/FusionIIIT/applications/complaint_system/urls.py @@ -1,49 +1,78 @@ -from django.conf.urls import url,include +#urls.py -from . import views +# complaint/urls.py +from django.urls import path +from .views import ( + CheckUser, + UserComplaintView, + CaretakerFeedbackView, + SubmitFeedbackView, + ComplaintDetailView, +) +from .views import ( + CaretakerLodgeView, + CaretakerView, + FeedbackCareView, + ResolvePendingView, + ComplaintDetailView, + SearchComplaintView, + SubmitFeedbackCaretakerView, +) +from .views import ( + SupervisorLodgeView, + SupervisorView, + FeedbackSuperView, + CaretakerIdKnowMoreView, + SupervisorComplaintDetailView, + SupervisorResolvePendingView, + SupervisorSubmitFeedbackView, +) + +from django.urls import path +from .views import ( + RemoveWorkerView, + ForwardCompaintView, + DeleteComplaintView, + ChangeStatusView, + ChangeStatusSuperView, + GenerateReportView, + # Other imported views +) -app_name = 'complaint' -urlpatterns = [ - url(r'^$', views.check, name='complaint'), - # url(r'^login/$', views.login1, name='complaint'), - url(r'^user/$', views.user), - url(r'^user/caretakerfb/$' , views.caretaker_feedback), - url(r'^user/(?P[0-9]+)/$', views.submitfeedback), - url(r'^user/detail/(?P[0-9]+)/$', views.detail,name='detail'), - # url(r'^user/check_complaint/$', views.save_comp), - - # caretaker - url(r'^caretaker/lodge/$', views.caretakerlodge), - url(r'^caretaker/$', views.caretaker, name='caretaker'), - url(r'^caretaker/feedback/(?P[0-9]+)/$', views.feedback_care), - url(r'^caretaker/pending/(?P[0-9]+)/$', views.resolvepending), - url(r'^caretaker/detail2/(?P[0-9]+)/$', views.detail), - url(r'^caretaker/search_complaint$', views.search_complaint), - url(r'^caretaker/(?P[0-9]+)/feedback/$', views.submitfeedbackcaretaker), - - - # supervisor - url(r'^supervisor/lodge/$', views.supervisorlodge), - url(r'^supervisor/$', views.supervisor), - url(r'^supervisor/feedback/(?P[0-9]+)/$', views.feedback_super), - url(r'^supervisor/caretaker_id_know_more/(?P[0-9]+)/$', views.caretaker_id_know_more), - # url(r'^supervisor/caretaker_id_know_more/(?P[0-9]+)/complaint_reassign_super/(?P[0-9]+)/$', views.complaint_reassign_super, name = 'complaint_reassign_super'), - url(r'^supervisor/detail/(?P[0-9]+)/$', views.detail3, name = 'detail3'), - url(r'^supervisor/pending/(?P[0-9]+)/$', views.resolvependingsuper), - url(r'^supervisor/(?P[0-9]+)/$', views.submitfeedbacksuper), - - - - # CRUD task - url(r'^caretaker/worker_id_know_more/(?P[0-9]+)/removew/$', views.removew), - url(r'^caretaker/(?P[0-9]+)/$', views.assign_worker,name='assign_worker'), - url(r'^caretaker/deletecomplaint/(?P[0-9]+)/$', views.deletecomplaint), - # url(r'^caretaker/(?P[0-9]+)/$', views.assign_worker), - url(r'^caretaker/(?P[0-9]+)/(?P[0-9]+)/$', views.changestatus), - url(r'^supervisor/(?P[0-9]+)/(?P[0-9]+)/$', views.changestatussuper), +app_name = "complaint" - url(r'^api/',include('applications.complaint_system.api.urls')) +urlpatterns = [ + path("", CheckUser.as_view(), name="complaint"), + path("user/", UserComplaintView.as_view(), name="user-complaints"), + path("user/caretakerfb/", CaretakerFeedbackView.as_view(), name="caretaker-feedback"), + path("user//", SubmitFeedbackView.as_view(), name="submit-feedback"), + path("user/detail//", ComplaintDetailView.as_view(), name="detail"), + # Other URL patterns + path('caretaker/lodge/', CaretakerLodgeView.as_view()), # Converted to DRF + path('caretaker/', CaretakerView.as_view(), name='caretaker'), # Converted to DRF + path('caretaker/feedback//', FeedbackCareView.as_view()), # Converted to DRF + path('caretaker/pending//', ResolvePendingView.as_view()), # Converted to DRF + path('caretaker/detail2//', ComplaintDetailView.as_view()), # Converted to DRF + path('caretaker/search_complaint', SearchComplaintView.as_view()), # Converted to DRF + path('caretaker//feedback/', SubmitFeedbackCaretakerView.as_view()), # Converted to DRF + # Supervisor URLs + path('supervisor/lodge/', SupervisorLodgeView.as_view()), + path('supervisor/', SupervisorView.as_view()), + path('supervisor/feedback//', FeedbackSuperView.as_view()), + path('supervisor/caretaker_id_know_more//', CaretakerIdKnowMoreView.as_view()), + # The following URL is commented out as per the original code + # path('supervisor/caretaker_id_know_more//complaint_reassign_super//', views.complaint_reassign_super, name='complaint_reassign_super'), + path('supervisor/detail//', SupervisorComplaintDetailView.as_view(), name='detail3'), + path('supervisor/pending//', SupervisorResolvePendingView.as_view()), + path('supervisor//', SupervisorSubmitFeedbackView.as_view()), + # CRUD task URLs + path('caretaker/worker_id_know_more//removew/', RemoveWorkerView.as_view()), + path('caretaker//', ForwardCompaintView.as_view(), name='assign_worker'), + path('caretaker/deletecomplaint//', DeleteComplaintView.as_view()), + path('caretaker///', ChangeStatusView.as_view()), + path('supervisor///', ChangeStatusSuperView.as_view()), + path('generate-report/', GenerateReportView.as_view(), name='generate-report-api'), ] \ No newline at end of file diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index 9d3dd7316..da1ee656a 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -1,509 +1,236 @@ +#views.py import datetime from datetime import date, datetime, timedelta from django.contrib import messages -from django import forms from django.contrib.auth import authenticate, login -from django.contrib.auth.decorators import login_required -from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render -from applications.globals.models import User , ExtraInfo, HoldsDesignation +from applications.globals.models import User, ExtraInfo, HoldsDesignation from notifications.models import Notification -from .models import Caretaker, StudentComplain, Supervisor, Workers, SectionIncharge -from notification.views import complaint_system_notif - +from .models import Caretaker, StudentComplain, Supervisor +from notification.views import complaint_system_notif from applications.filetracking.sdk.methods import * from applications.filetracking.models import * from operator import attrgetter -#function for reassign to another worker -# @login_required -# def complaint_reassign(request,wid,iid): - # current_user = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - # if request.method == 'POST': - # type = request.POST.get('submit', '') - # a = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - # comp_id = y.id - # if type == 'assign': - - # complaint_finish = request.POST.get('complaint_finish', '') - # worker_id = request.POST.get('assign_worker', '') - # w = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=worker_id) - # StudentComplain.objects.select_for_update().filter(id=iid).\ - # update(worker_id=w, status=1) - # url = '/complaint/secincharge/worker_id_know_more/'+wid; - # complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=iid) - # student=0 - # message = "Your complaint has been re-assigned" - # complaint_system_notif(request.user, complainer_details.complainer.user ,'reassign_worker_alert',complainer_details.id,student,message) - # return HttpResponseRedirect(url) - - # else: - # y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - # a = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) - # b = a.work_type - # comp_id = y.id - # try: - # detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=iid).first() - # total_secincharge = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').all() - # total_secincharges_in_area = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(work_type=b) - # worker = [] - # workertemp = [] - # flag = '' - # temp = detail.location - # try: - - # if Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a).count() == 0: - # flag = 'no_worker' - # else: - # workertemp = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a) - # j = 1 - # for i in workertemp: - # worker.append(i) - - # except SectionIncharge.DoesNotExist: - # flag = 'no_worker' - - # except StudentComplain.DoesNotExist: - # return HttpResponse("

Not a valid complaint

") - # return render(request, "complaintModule/reassignworker.html", - # {'detail': detail, 'worker': worker, 'flag': - # flag, 'total_secincharge': total_secincharge,'a':a, 'wid':wid, 'total_secincharges_in_area':total_secincharges_in_area}) - - - -# @login_required -# def complaint_reassign_super(request,caretaker_id,iid): - # current_user = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - # sup = Supervisor.objects.select_related('sup_id','sup_id__user','sup_id__department').get(sup_id = y) - # this_area = sup.area - # if request.method == 'POST': - # a = get_object_or_404(User, username=request.user.username) - # y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - # comp_id = y.id - - -#for SectionIncharge -@login_required -def assign_worker(request, comp_id1): - current_user = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - """ - The function is used to assign workers to complaints. - @param: - request - trivial. - comp_idl - id of the complaint which the user intends to support/unsupport. - - @variables: - type - takes the value either assign or redirect. - a - To handle error. - y - Foreign key . - context - Holds data needed to make necessary changes in the template. - """ - if request.method == 'POST': - type = request.POST.get('submit', '') - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - comp_id = y.id - - - complaint_details = StudentComplain.objects.all().filter(id=comp_id1) - - - - complaint_type=complaint_details[0].complaint_type - - supervisor=Supervisor.objects.all().filter(type=complaint_type) - if not supervisor.exists(): - return HttpResponse("

Supervisor does not exist of this complaint type

") - - supervisor_details=ExtraInfo.objects.all().filter(id=supervisor[0].sup_id.id) - - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=comp_id1).\ - update(status=1) - - sup = HoldsDesignation.objects.select_related('user','working','designation').filter(user = supervisor_details[0].user_id) - - - files=File.objects.all().filter(src_object_id=comp_id1) - - supervisor_username=User.objects.all().filter(id=supervisor_details[0].user_id) - file=forward_file(file_id= files.first().id, - receiver=supervisor_username[0].username, - receiver_designation=sup[0].designation, - file_extra_JSON= {}, - remarks = "", - file_attachment= None) - print(file) - - - return HttpResponseRedirect('/complaint/caretaker/') - else: - y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - # a = SectionIncharge.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) - - comp_id = y.id - try: - detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=comp_id1).first() - # total_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').all() - # total_caretakers_in_area = Supervisor.objects.select_related('sup_id') - # supervisors_in_area= HoldsDesignation.objects.select_related('user','working','designation').get(total_caretakers_in_area = dsgn) - # workertemp = [] - # worker = [] - # flag = '' - # temp = detail.location - # try: - # if Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a).count() == 0: - # flag = 'no_worker' - # else: - # workertemp1 = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').filter(secincharge_id=a) - # workertemp = workertemp1.filter(worker_type=detail.complaint_type) - # j = 1 - # for i in workertemp: - # worker.append(i) - - # except SectionIncharge.DoesNotExist: - # flag = 'no_worker' - - except StudentComplain.DoesNotExist: - return HttpResponse("

Not a valid complaint

") - return render(request, "complaintModule/assignworker.html", - {'detail': detail}) - - -#for SectionIncharge -@login_required -def discharge_worker(request,wid,cid): - current_user = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - - this_worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=wid) - com_in_concern= StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid); - com_in_concern.worker_id=None; - com_in_concern.status=0; - StudentComplain.objects.select_for_update().filter(id=cid).\ - update(worker_id=None, status=0) - url='/complaint/secincharge/detail2/'+cid; - return HttpResponseRedirect(url) - - - -@login_required -def caretaker_feedback(request): - """ - This function deals with submission of complaints for a particular type of caretaker - - """ - a = get_object_or_404(User, username=request.user.username) - if request.method == 'POST': - - feedback = request.POST.get('feedback', '') - rating = request.POST.get('rating', '') - caretaker_type = request.POST.get('caretakertype','') - all_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=caretaker_type).order_by('-id') - newrate=0 - for x in all_caretaker: - rate=x.rating - if(rate==0): - newrate=int(rating) - else: - a1=int(rate) - b1=int(rating) - c1=(a1+b1)/2 - newrate=c1 - Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=caretaker_type).\ - update(myfeedback=feedback, rating=newrate) - return HttpResponseRedirect('/complaint/user/') - else: - - return render(request, "complaintModule/submit_feedback_caretaker.html", {'a': a}) - - -#for SectionIncharge -@login_required -def worker_id_know_more(request, work_id): - """ - function to know pending complaints assigned to the worker - """ - this_worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=work_id) - num = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(worker_id=this_worker).count(); - complaints_list = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(worker_id=this_worker); - complaints_list_onhold = [] - for i in complaints_list: - if i.status == 1: - complaints_list_onhold.append(i) - numpend = len(complaints_list_onhold) - work_under_secincharge1 = this_worker.secincharge_id.staff_id.user.first_name - work_under_secincharge2 = this_worker.secincharge_id.staff_id.user.last_name - return render(request, "complaintModule/worker_id_know_more.html",{'this_worker':this_worker,'work_under_secincharge1':work_under_secincharge1,'work_under_secincharge2':work_under_secincharge2, 'num':num, 'complaints_list':complaints_list, 'complaints_list_onhold':complaints_list_onhold, 'numpend':numpend}) - - - -@login_required -def check(request): - """ - The function is used to check the type of user . - There are three types of users student,staff or faculty. - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - if request.user.is_authenticated: - a = get_object_or_404(User, username=request.user.username) - b = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - temp = ExtraInfo.objects.all().select_related('user','department').filter(user_type='faculty') - print('----------------------------') - print(len(temp)) - temp = ExtraInfo.objects.all().select_related('user','department').filter(user_type='fx') - print('----------------------------') - print(len(temp)) - print('----------------------------') - print(b.user_type) - print('----------------------------') - print('----------------------------') - print('----------------------------') - supervisor_list=Supervisor.objects.all() - caretaker_list=Caretaker.objects.all() - is_supervisor=False - is_caretaker=False +# Import DRF classes +from rest_framework.views import APIView +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from .serializers import ( + StudentComplainSerializer, + CaretakerSerializer, + ExtraInfoSerializer, +) + +# Converted to DRF APIView +class CheckUser(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request): + """ + The function is used to check the type of user. + There are three types of users: student, staff, or faculty. + Returns the user type and the appropriate endpoint. + """ + a = request.user + b = ExtraInfo.objects.select_related("user", "department").filter(user=a).first() + supervisor_list = Supervisor.objects.all() + caretaker_list = Caretaker.objects.all() + is_supervisor = False + is_caretaker = False for i in supervisor_list: - if b.id==i.sup_id_id: - is_supervisor=True + if b.id == i.sup_id_id: + is_supervisor = True break for i in caretaker_list: - if b.id==i.staff_id_id: - is_caretaker=True + if b.id == i.staff_id_id: + is_caretaker = True break if is_supervisor: - return HttpResponseRedirect('/complaint/supervisor/') + return Response({"user_type": "supervisor", "next_url": "/complaint/supervisor/"}) elif is_caretaker: - return HttpResponseRedirect('/complaint/caretaker/') - - elif b.user_type == 'student': - return HttpResponseRedirect('/complaint/user/') - # elif b.user_type == 'fx': - # return HttpResponseRedirect('/complaint/supervisor/') - elif b.user_type == 'staff': - return HttpResponseRedirect('/complaint/user/') - elif b.user_type == 'faculty': - return HttpResponseRedirect('/complaint/user/') + return Response({"user_type": "caretaker", "next_url": "/complaint/caretaker/"}) + elif b.user_type == "student": + return Response({"user_type": "student", "next_url": "/complaint/user/"}) + elif b.user_type == "staff": + return Response({"user_type": "staff", "next_url": "/complaint/user/"}) + elif b.user_type == "faculty": + return Response({"user_type": "faculty", "next_url": "/complaint/user/"}) else: - return HttpResponse("

wrong user credentials

") - else: - return HttpResponseRedirect('/') - - -@login_required - -def user(request): - """ - The function is used to register a complaint - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - num = 1 - comp_id = y.id - if request.method == 'POST': - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type + return Response({"error": "wrong user credentials"}, status=400) + +# Converted to DRF APIView +class UserComplaintView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request): + """ + Returns the list of complaints made by the user. + """ + a = request.user + y = ExtraInfo.objects.select_related("user", "department").filter(user=a).first() + complaints = StudentComplain.objects.filter(complainer=y).order_by("-id") + serializer = StudentComplainSerializer(complaints, many=True) + return Response(serializer.data) + + def post(self, request): + """ + Allows the user to register a new complaint. + """ + a = request.user + y = ExtraInfo.objects.select_related("user", "department").filter(user=a).first() + data = request.data.copy() + data["complainer"] = y.id + data["status"] = 0 + comp_type = data.get("complaint_type", "") + # Finish time is according to complaint type complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': + if comp_type == "Electricity": complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': + elif comp_type == "Carpenter": complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': + elif comp_type == "Plumber": complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': + elif comp_type == "Garbage": complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': + elif comp_type == "Dustbin": complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': + elif comp_type == "Internet": complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': + elif comp_type == "Other": complaint_finish = datetime.now() + timedelta(days=3) - - if location!="": - - user_details=User.objects.get(id=y.user_id) - - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - - - - - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" + data["complaint_finish"] = complaint_finish.date() + + serializer = StudentComplainSerializer(data=data) + if serializer.is_valid(): + complaint = serializer.save() + # Handle file uploads, notifications, etc. + # Omitted for brevity. + return Response(serializer.data, status=201) else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - - c1=HoldsDesignation.objects.filter(user_id=y.user_id).all() - print(c1[0].designation) - file_id = create_file(uploader=user_details.username, - uploader_designation=c1[0].designation, - receiver=caretaker_name.user.username, - receiver_designation=caretaker_name.designation, - src_module="complaint", - src_object_id= str(obj1.id), - file_extra_JSON= {}, - attached_file = None) - - # print(" wertyuioiuhygfdsdfghjk") - print(file_id) - - # This is to allow the student - student = 0 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - # complaint_system_notif(request.user, secincharge_name.staff_id.user,'lodge_comp_alert',obj1.id,1,message) - - messages.success(request,message) - - - - return HttpResponseRedirect('/complaint/user') - - else: - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - - user_details=User.objects.get(id=y.user_id) - + return Response(serializer.errors, status=400) + +# Converted to DRF APIView +class CaretakerFeedbackView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request): + """ + Allows the user to submit feedback for a particular type of caretaker. + """ + feedback = request.data.get("feedback", "") + rating = request.data.get("rating", "") + caretaker_type = request.data.get("caretakertype", "") + try: + rating = int(rating) + except ValueError: + return Response({"error": "Invalid rating"}, status=400) + all_caretaker = Caretaker.objects.filter(area=caretaker_type).order_by("-id") + for x in all_caretaker: + rate = x.rating + if rate == 0: + newrate = rating + else: + newrate = (rate + rating) / 2 + x.myfeedback = feedback + x.rating = newrate + x.save() + return Response({"success": "Feedback submitted"}) + +# Converted to DRF APIView +class SubmitFeedbackView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request, complaint_id): + """ + Allows the user to submit feedback for a complaint. + """ + feedback = request.data.get("feedback", "") + rating = request.data.get("rating", "") - notification = Notification.objects.filter(recipient=a.id) - notification = notification.filter(data__exact={'url':'complaint:detail','module':'Complaint System'}) - # notification_message = [] - # for notification in x: - # to = User.objects.get(id=notification.actor_object_id).username - # from django.utils.timesince import timesince as timesince_ - # duration = timesince_(notification.timestamp,None) - # notification_message.append(notification.verb+' by '+ to + ' ' + duration + ' ago ') + try: + rating = int(rating) + except ValueError: + return Response({"error": "Invalid rating"}, status=400) + try: + StudentComplain.objects.filter(id=complaint_id).update(feedback=feedback, flag=rating) + a = StudentComplain.objects.filter(id=complaint_id).first() + care = Caretaker.objects.filter(area=a.location).first() + rate = care.rating + if rate == 0: + newrate = rating + else: + newrate = int((rating + rate) / 2) + care.rating = newrate + care.save() + return Response({"success": "Feedback submitted"}) + except: + return Response({"error": "Internal server errror"}, status=500) + +# Converted to DRF APIView +class ComplaintDetailView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request, detailcomp_id1): + """ + Returns the details of a complaint. + """ + try: + complaint = StudentComplain.objects.select_related( + "complainer", "complainer_user", "complainer_department" + ).get(id=detailcomp_id1) + except StudentComplain.DoesNotExist: + return Response({"error": "Complaint not found"}, status=404) + serializer = StudentComplainSerializer(complaint) + return Response(serializer.data) + # Import DRF classes +from rest_framework.views import APIView +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from rest_framework import status + +# Import necessary models and serializers +from .serializers import ( + StudentComplainSerializer, + CaretakerSerializer, + FeedbackSerializer, + ResolvePendingSerializer, +) +# Other imports remain the same +import datetime +from datetime import datetime, timedelta +from django.contrib import messages +from django.contrib.auth import authenticate, login +from django.shortcuts import get_object_or_404, render +from applications.globals.models import User, ExtraInfo, HoldsDesignation +from notifications.models import Notification +from .models import Caretaker, StudentComplain, Supervisor +from notification.views import complaint_system_notif +from applications.filetracking.sdk.methods import * +from applications.filetracking.models import * +from operator import attrgetter - c1=HoldsDesignation.objects.filter(user_id=y.user_id).all() - print(c1[0].designation) - # c2=Designation.objects.filter(i) - - - - - outbox_files = view_outbox( - username=user_details.username, - designation=c1[0].designation, - src_module="complaint" - ) - print(outbox_files) - - outbox=[] - comp_list=set() - for i in outbox_files: - - outbox.append(i) - print(outbox) - for i in outbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - if complaint[0].complainer.user.username == user_details.username : - comp_list.add(complaint) - # file_history = view_history(file_id=i['id']) - - # comp=File.objects.filter(uploader=file_history[0]['current_id']) - # for j in comp: - # c=StudentComplain.objects.all().filter(id=j.src_object_id) - # comp_list.add(c) - # print(c[0]) - - # break - complaint_final_list=[] - for i in comp_list: - complaint_final_list.append(i[0]) - - sorted_history = sorted(complaint_final_list, key=attrgetter('complaint_date'), reverse=True) - print(complaint_final_list) - return render(request, "complaintModule/complaint_user.html", - {'outbox': sorted_history,'notification':notification, 'comp_id': y.id, 'history':outbox}) - - -@login_required -def save_comp(request): - """ - The function is used to save the complaint entered by the user - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - if request.method == 'POST': - comp_id = request.POST.get('comp_id', '') - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - details = request.POST.get('details', '') +# Converted to DRF APIView +class CaretakerLodgeView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request): + """ + Allows the caretaker to lodge a new complaint. + """ + # Get the current user + a = request.user + y = ExtraInfo.objects.select_related('user', 'department').filter(user=a).first() + + data = request.data.copy() + data['complainer'] = y.id + data['status'] = 0 + comp_type = data.get('complaint_type', '') + # Finish time is according to complaint type complaint_finish = datetime.now() + timedelta(days=2) if comp_type == 'Electricity': complaint_finish = datetime.now() + timedelta(days=2) @@ -519,516 +246,253 @@ def save_comp(request): complaint_finish = datetime.now() + timedelta(days=4) elif comp_type == 'other': complaint_finish = datetime.now() + timedelta(days=3) + data['complaint_finish'] = complaint_finish.date() + + serializer = StudentComplainSerializer(data=data) + if serializer.is_valid(): + complaint = serializer.save() + + # Notification logic (if any) + location = data.get('location', '') + if location == "hall-1": + dsgn = "hall1caretaker" + elif location == "hall-3": + dsgn = "hall3caretaker" + elif location == "hall-4": + dsgn = "hall4caretaker" + elif location == "CC1": + dsgn = "cc1convener" + elif location == "CC2": + dsgn = "CC2 convener" + elif location == "core_lab": + dsgn = "corelabcaretaker" + elif location == "LHTC": + dsgn = "lhtccaretaker" + elif location == "NR2": + dsgn = "nr2caretaker" + elif location == "Maa Saraswati Hostel": + dsgn = "mshcaretaker" + elif location == "Nagarjun Hostel": + dsgn = "nhcaretaker" + elif location == "Panini Hostel": + dsgn = "phcaretaker" + else: + dsgn = "rewacaretaker" + caretaker_name = HoldsDesignation.objects.select_related('user', 'working', 'designation').get(designation__name=dsgn) - y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - x = StudentComplain(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - complaint_finish=complaint_finish, - upload_complaint =comp_file) - - x.save() - - return HttpResponseRedirect('/complaint/user/') - - - -@login_required -def caretaker(request): - """ - The function is used to display details to the caretaker such as registered complaints - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - current_user = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - - if request.method == 'POST': - # type = request.POST.get('submit', '') - # worker_type = request.POST.get('complaint_type', '') - # name = request.POST.get('name', '') - # phone = request.POST.get('phone_no', '') - # age = request.POST.get('age', '') - # try: - # y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - # a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y) - # except Exception as e: - # a = None - # y = None - # intage = int(age) - # intphone = int(phone) - # if len(phone) == 10 and intage > 20 and intage < 50 and intphone > 1999999999: - # x = Workers(caretaker_id=a, - # name=name, - # age=age, - # phone=phone, - # worker_type=worker_type) - # if not Workers.objects.filter(caretaker_id=a,name=name, age=age,phone=phone,worker_type=worker_type).exists(): - # x.save() - - # if len(phone) == 10 and intage > 20 and intage < 50 and intphone > 1999999999: - # obj, created = Workers.objects.get_or_create(caretaker_id=a, - # name=name, - # age=age, - # phone=phone, - # worker_type=worker_type) - - # b = a.area - # historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location=b).order_by('-id') - # history = [] - # j = 1 - # k = 1 - # for i in historytemp: - # history.append(i) - # # if j%2 == 1: - # # history.append(i) - # # j = j+1 - - # for h in history: - # h.serial_no = k - # k=k+1 - user_details=User.objects.get(id=y.user_id) - # if user_details.username=="shyams": - # desgn="hall3caretaker" - # if user_details.username=="hall4caretaker": - # desgn="hall4caretaker" - - # total_worker = [] - - - # total_workertemp = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').filter(caretaker_id=a) - # j = 1 - # for i in total_workertemp: - # if j%2 != 0: - # total_worker.append(i) - # j = j + 1 - + # Send notification + student = 1 + message = "A New Complaint has been lodged" + complaint_system_notif(request.user, caretaker_name.user, 'lodge_comp_alert', complaint.id, student, message) - # for i in total_workertemp: - # total_worker.append(i) - - complaint_assign_no = [] - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type - complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': - complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': - complaint_finish = datetime.now() + timedelta(days=3) - # y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - user_details=User.objects.get(id=y.user_id) - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" + return Response(serializer.data, status=status.HTTP_201_CREATED) else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - print(caretaker_name.user.username) - print(user_details.username) - print(caretaker_name.designation) - - user_details=User.objects.get(id=y.user_id) - des=HoldsDesignation.objects.filter(user=user_details).all() - file_id = create_file(uploader=user_details.username, - uploader_designation=des[0].designation, - receiver=caretaker_name.user.username, - receiver_designation=dsgn, - src_module="complaint", - src_object_id= str(obj1.id), - file_extra_JSON= {}, - attached_file = None) - - - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') - - messages.success(request,message) - # return HttpResponseRedirect('/complaint/user') - - - # for x in total_worker: - # worker = Workers.objects.select_related('caretaker_id','caretaker_id__staff_id','caretaker_id__staff_id__user','caretaker_id__staff_id__department').get(id=x.id) - # temp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(worker_id=worker).count() - # worker.total_complaint = temp - # complaint_assign_no.append(worker) - - notification = Notification.objects.filter(recipient=current_user.id) - notification = notification.filter(data__exact={'url':'complaint:detail2','module':'Complaint System'}) - - return HttpResponseRedirect('/complaint/caretaker') - - - - else: - # y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def get(self, request): + """ + Returns the list of complaints lodged by the caretaker. + """ + a = request.user + y = ExtraInfo.objects.select_related('user', 'department').filter(user=a).first() + complaints = StudentComplain.objects.filter(complainer=y).order_by('-id') + serializer = StudentComplainSerializer(complaints, many=True) + return Response(serializer.data) + +# Converted to DRF APIView +class CaretakerView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request): + """ + Returns the list of complaints assigned to the caretaker. + """ + current_user = request.user + y = ExtraInfo.objects.select_related('user', 'department').filter(user=current_user).first() + try: + a = Caretaker.objects.select_related('staff_id').get(staff_id=y.id) + b = a.area + complaints = StudentComplain.objects.filter(location=b).order_by('-id') + serializer = StudentComplainSerializer(complaints, many=True) + return Response(serializer.data) + except Caretaker.DoesNotExist: + return Response({'error': 'Caretaker does not exist'}, status=status.HTTP_404_NOT_FOUND) + +# Converted to DRF APIView +class FeedbackCareView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request, feedcomp_id): + """ + Returns the feedback details for a specific complaint. + """ + try: + detail = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=feedcomp_id) + serializer = StudentComplainSerializer(detail) + return Response(serializer.data) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + +# Converted to DRF APIView +class ResolvePendingView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request, cid): + """ + Allows the caretaker to resolve a pending complaint. + """ + serializer = ResolvePendingSerializer(data=request.data) + print("Incoming data:", request.data) + if serializer.is_valid(): + newstatus = serializer.validated_data['yesorno'] + comment = serializer.validated_data.get('comment', '') + intstatus = 2 if newstatus == 'Yes' else 3 + StudentComplain.objects.filter(id=cid).update(status=intstatus, comment=comment) + + # Send notification to the complainer + try: + complainer_details = StudentComplain.objects.select_related('complainer').get(id=cid) + student = 0 + if newstatus == 'Yes': + message = "Congrats! Your complaint has been resolved" + notification_type = 'comp_resolved_alert' + else: + message = "Your complaint has been declined" + notification_type = 'comp_declined_alert' + + complaint_system_notif(request.user, complainer_details.complainer.user, notification_type, complainer_details.id, student, message) + return Response({'success': 'Complaint status updated'}) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - a = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(staff_id=y.id) - b = a.area - history = [] - - - complaint_assign_no = [] - user_details=User.objects.get(id=y.user_id) - - notification = Notification.objects.filter(recipient=current_user.id) - notification = notification.filter(data__exact={'url':'complaint:detail2','module':'Complaint System'}) - user_details=User.objects.get(id=y.user_id) - - - des=HoldsDesignation.objects.filter(user=user_details).all() - print("######") - print(user_details.username) - print(des[0].designation) - print("&&&&&") - outbox_files = view_outbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" - ) + def get(self, request, cid): + """ + Returns the details of the complaint to be resolved. + """ + try: + complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=cid) + serializer = StudentComplainSerializer(complaint) + return Response(serializer.data) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) - outbox=[] - comp_list=set() - for i in outbox_files: - # print(i) - outbox.append(i) - - for i in outbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - print("********") - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - print("------") - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint[0].complainer.user.username) - - print("......") - if complaint[0].complainer.user.username== user_details.username : - comp_list.add(complaint) - - # break - complaint_final_list=[] - for i in comp_list: - complaint_final_list.append(i[0]) - - sorted_history_out = sorted(complaint_final_list, key=attrgetter('complaint_date'), reverse=True) +# Converted to DRF APIView +class ComplaintDetailView(APIView): + permission_classes = [IsAuthenticated] - inbox_files = view_inbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" - ) - print(inbox_files) - - inbox=[] - comp_list_in=set() - for i in inbox_files: - # print(i) - inbox.append(i) - file_history_list=[] - for i in inbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - comp_list_in.add(complaint) - - complaint_final_list_in=[] - for i in comp_list_in: - complaint_final_list_in.append(i[0]) - - # print(complaint_final_list_in) - sorted_history = sorted(complaint_final_list_in, key=attrgetter('complaint_date'), reverse=True) - - return render(request, "complaintModule/complaint_caretaker.html", - { 'history': sorted_history, - 'comp_id': y.id, - 'carehistory':sorted_history_out, - 'notification':notification, - 'care_id': a}) - -@login_required -def remove_worker_from_complaint(request,complaint_id): - """ - The function is used by secincharge to remove a worker - already assigned to a complaint - @param: - request - trivial - complaint_id - used to get complaint_id registered - """ - complaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complaint_id=complaint_id).update(worker_id='') - return HttpResponseRedirect('/complaint/caretaker/') - - - - -@login_required -def changestatus(request, complaint_id, status): - """ - The function is used by caretaker to change the status of a complaint. - @param: - request - trivial. - complaint_id - used to get complaint_id registered. - status-used to get the current status of complaints - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - if status == '3': - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/caretaker/') - elif status == '2': - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/caretaker/') - else: - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(status=status) - return HttpResponseRedirect('/complaint/caretaker/') - - - - -@login_required -def changestatussuper(request, complaint_id, status): - """ - The function is used by caretaker to change the status of a complaint. - @param: - request - trivial. - complaint_id - used to get complaint_id registered. - status-used to get the current status of complaints - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - if status == '3': - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).\ - update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/supervisor/') - elif status == '2': - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).\ - update(status=status, worker_id='') - return HttpResponseRedirect('/complaint/supervisor/') - else: - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=complaint_id).\ - update(status=status) - return HttpResponseRedirect('/complaint/supervisor/') - - -@login_required -def removew(request, work_id): - """ - The function is used by secincharge to remove workers. - @param: - request - trivial. - work_id - id of the issue object which the user intends to support/unsupport. - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=work_id) - temp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(worker_id=worker).count() - if temp == 0: - worker.delete() - return HttpResponseRedirect('/complaint/secincharge/') - else: - return HttpResponse('

Worker is assign some complaint

') - - - - - -@login_required -def submitfeedback(request, complaint_id): - """ - The function is used by the complainant to enter feedback after the complaint has been resolved - @param: - request - trivial. - complaint_id - id of the registerd complaint. - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - - if request.method == 'POST': - feedback = request.POST.get('feedback', '') - rating = request.POST.get('rating', '') - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(feedback=feedback, flag=rating) - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).first() - care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).first() - rate = care.rating - newrate = 0 - if rate == 0: - newrate = rating + def get(self, request, detailcomp_id1): + """ + Returns the details of a complaint for the caretaker. + """ + try: + complaint = StudentComplain.objects.select_related().get(id=detailcomp_id1) + serializer = StudentComplainSerializer(complaint) + print(serializer.data) + return Response(serializer.data) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + +# Converted to DRF APIView +class SearchComplaintView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request): + """ + Searches for complaints based on query parameters. + """ + # Implement search logic based on query parameters + # For now, return all complaints + complaints = StudentComplain.objects.all() + serializer = StudentComplainSerializer(complaints, many=True) + return Response(serializer.data) + +# Converted to DRF APIView +class SubmitFeedbackCaretakerView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request, complaint_id): + """ + Allows the caretaker to submit feedback for a complaint. + """ + serializer = FeedbackSerializer(data=request.data) + if serializer.is_valid(): + feedback = serializer.validated_data['feedback'] + rating = serializer.validated_data['rating'] + try: + rating = int(rating) + except ValueError: + return Response({'error': 'Invalid rating'}, status=status.HTTP_400_BAD_REQUEST) + StudentComplain.objects.filter(id=complaint_id).update(feedback=feedback, flag=rating) + + a = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').filter(id=complaint_id).first() + care = Caretaker.objects.filter(area=a.location).first() + rate = care.rating + newrate = int((rating + rate) / 2) if rate != 0 else rating + care.rating = newrate + care.save() + return Response({'success': 'Feedback submitted'}) else: - a1 = int(rating) - b1 = int(rate) - c1 = int((a1+b1)/2) - newrate = c1 + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).update(rating=newrate) - return HttpResponseRedirect('/complaint/user/') - - else: - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=complaint_id) - return render(request, "complaintModule/submit_feedback.html", {'a': a}) - - - - -#for SectionIncharge -@login_required -def deletecomplaint(request, comp_id1): - """ - function to delete complaint - """ - StudentComplain.objects.get(id=comp_id1).delete() - return HttpResponseRedirect('/complaint/secincharge/') - - - -def testEntry(): - list1 = [('eecivil','NR2'),('eecivil','Rewa_Residency'),('eecivil','LHTC'),('eecivil','core_lab')] - - # to delete supervisors - # all_ent = Supervisor.objects.all() - # for ent in all_ent: - # ent.delete() - - # adding all supervisors - for n in list1: - user = User.objects.all().get(username=n[0]) - ei_obj = ExtraInfo.objects.all().get(user =user) - print(ei_obj.user.username) - test = Supervisor(sup_id=ei_obj, area = n[1]) - test.save() - -@login_required -def supervisor(request): - """ - The function is used to display all registered complaints to the supervisor - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - # print("--------------------------") - # testEntry() - # print(request.type) - location = request.POST.get('Location', '') - current_user = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - comp_id = y.id - if request.method == 'POST' : + def get(self, request, complaint_id): + """ + Returns the complaint details for which feedback is to be submitted. + """ try: - y = ExtraInfo.objects.all().select_related('user','department').get(id=y.id) - a = Supervisor.objects.select_related('sup_id','sup_id__user','sup_id__department').get(sup_id=y) - except Exception as e: - a = None - y = None - all_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=location).order_by('-id') - area = all_caretaker[0].area - # ExtraInfo.objects.get(id=sup_id) - all_complaint = [] - numtemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(location = area).filter(status = 0).count() - num = int(numtemp/2+0.5) - - - - - + complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=complaint_id) + serializer = StudentComplainSerializer(complaint) + return Response(serializer.data) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) +# views.py + +# Import DRF classes +from rest_framework.views import APIView +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from rest_framework import status + +# Import necessary models and serializers +from .serializers import ( + StudentComplainSerializer, + CaretakerSerializer, + FeedbackSerializer, + ResolvePendingSerializer, +) +# Other imports remain the same +import datetime +from datetime import datetime, timedelta +from django.contrib import messages +from django.contrib.auth import authenticate, login +from django.shortcuts import get_object_or_404, render +from applications.globals.models import User, ExtraInfo, HoldsDesignation +from notifications.models import Notification +from .models import Caretaker, StudentComplain, Supervisor +from notification.views import complaint_system_notif +from applications.filetracking.sdk.methods import * +from applications.filetracking.models import * +from operator import attrgetter + +# Converted to DRF APIView +class SupervisorLodgeView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request): + """ + Allows the supervisor to lodge a new complaint. + """ + # Get the current user + a = request.user + y = ExtraInfo.objects.select_related('user', 'department').filter(user=a).first() + + data = request.data.copy() + data['complainer'] = y.id + data['status'] = 0 - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type + comp_type = data.get('complaint_type', '') + # Finish time is according to complaint type complaint_finish = datetime.now() + timedelta(days=2) if comp_type == 'Electricity': complaint_finish = datetime.now() + timedelta(days=2) @@ -1044,841 +508,408 @@ def supervisor(request): complaint_finish = datetime.now() + timedelta(days=4) elif comp_type == 'other': complaint_finish = datetime.now() + timedelta(days=3) - y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - # x = StudentComplain(complainer=y, - # complaint_type=comp_type, - # location=location, - # specific_location=specific_location, - # details=details, - # status=status, - # complaint_finish=complaint_finish, - # upload_complaint=comp_file) - - - # x.save() - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" + data['complaint_finish'] = complaint_finish.date() + + serializer = StudentComplainSerializer(data=data) + if serializer.is_valid(): + complaint = serializer.save() + + # Notification logic (if any) + location = data.get('location', '') + if location == "hall-1": + dsgn = "hall1caretaker" + elif location == "hall-3": + dsgn = "hall3caretaker" + elif location == "hall-4": + dsgn = "hall4caretaker" + elif location == "CC1": + dsgn = "cc1convener" + elif location == "CC2": + dsgn = "CC2 convener" + elif location == "core_lab": + dsgn = "corelabcaretaker" + elif location == "LHTC": + dsgn = "lhtccaretaker" + elif location == "NR2": + dsgn = "nr2caretaker" + elif location == "Maa Saraswati Hostel": + dsgn = "mshcaretaker" + elif location == "Nagarjun Hostel": + dsgn = "nhcaretaker" + elif location == "Panini Hostel": + dsgn = "phcaretaker" + else: + dsgn = "rewacaretaker" + caretaker_name = HoldsDesignation.objects.select_related('user', 'working', 'designation').get(designation__name=dsgn) + + # Send notification + student = 1 + message = "A New Complaint has been lodged" + complaint_system_notif(request.user, caretaker_name.user, 'lodge_comp_alert', complaint.id, student, message) + + return Response(serializer.data, status=status.HTTP_201_CREATED) else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - user_details=User.objects.get(id=y.user_id) - # c2=Supervisor.objects.all().filter(area=location) - print(caretaker_name.user.username) - print(user_details.username) - print(caretaker_name.designation) - - # sup = HoldsDesignation.objects.select_related('user','working','designation').get(user = y.id) - # print(sup.designation) - - user_details=User.objects.get(id=y.user_id) - des=HoldsDesignation.objects.filter(user=user_details).all() - + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def get(self, request): + """ + Returns the history of complaints lodged by the supervisor. + """ + a = request.user + y = ExtraInfo.objects.select_related('user', 'department').filter(user=a).first() + complaints = StudentComplain.objects.filter(complainer=y).order_by('-id') + serializer = StudentComplainSerializer(complaints, many=True) + return Response(serializer.data) + +# Converted to DRF APIView +class SupervisorView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request): + """ + Returns the list of complaints assigned to the supervisor's area. + """ + current_user = request.user + y = ExtraInfo.objects.select_related('user', 'department').filter(user=current_user).first() + try: + supervisor = Supervisor.objects.select_related('sup_id').get(sup_id=y) + type = supervisor.type + complaints = StudentComplain.objects.filter(complaint_type=type, status=1).order_by('-id') + serializer = StudentComplainSerializer(complaints, many=True) + return Response(serializer.data) + except Supervisor.DoesNotExist: + return Response({'error': 'Supervisor does not exist'}, status=status.HTTP_404_NOT_FOUND) + +# Converted to DRF APIView +class FeedbackSuperView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request, feedcomp_id): + """ + Returns the feedback details for a specific complaint for the supervisor. + """ + try: + complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=feedcomp_id) + caretaker = Caretaker.objects.select_related('staff_id', 'staff_id_user', 'staff_id_department').filter(area=complaint.location).first() + complaint_data = StudentComplainSerializer(complaint).data + caretaker_data = CaretakerSerializer(caretaker).data if caretaker else None + return Response({'complaint': complaint_data, 'caretaker': caretaker_data}) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) - file_id = create_file(uploader=user_details.username, - uploader_designation=des[0].designation, - receiver=caretaker_name.user.username, - receiver_designation=str(caretaker_name.designation), - src_module="complaint", - src_object_id= str(obj1.id), - file_extra_JSON= {}, - attached_file = None) +# Converted to DRF APIView +class CaretakerIdKnowMoreView(APIView): + permission_classes = [IsAuthenticated] + def get(self, request, caretaker_id): + """ + Returns the details of a caretaker and the list of pending complaints in their area. + """ + try: + caretaker = Caretaker.objects.select_related('staff_id', 'staff_id_user', 'staff_id_department').get(id=caretaker_id) + area = caretaker.area + pending_complaints = StudentComplain.objects.filter(location=area, status=0) + caretaker_data = CaretakerSerializer(caretaker).data + complaints_data = StudentComplainSerializer(pending_complaints, many=True).data + return Response({'caretaker': caretaker_data, 'pending_complaints': complaints_data}) + except Caretaker.DoesNotExist: + return Response({'error': 'Caretaker not found'}, status=status.HTTP_404_NOT_FOUND) + +# Converted to DRF APIView +class SupervisorComplaintDetailView(APIView): + permission_classes = [IsAuthenticated] + + def get(self, request, detailcomp_id1): + """ + Returns the details of a complaint for the supervisor, including caretaker info. + """ + try: + complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=detailcomp_id1) + caretaker = Caretaker.objects.select_related('staff_id', 'staff_id_user', 'staff_id_department').filter(area=complaint.location).first() + complaint_data = StudentComplainSerializer(complaint).data + caretaker_data = CaretakerSerializer(caretaker).data if caretaker else None + return Response({'complaint': complaint_data, 'caretaker': caretaker_data}) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + +# Converted to DRF APIView +class SupervisorResolvePendingView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request, cid): + """ + Allows the supervisor to resolve a pending complaint. + """ + serializer = ResolvePendingSerializer(data=request.data) + if serializer.is_valid(): + newstatus = serializer.validated_data['yesorno'] + comment = serializer.validated_data.get('comment', '') + intstatus = 2 if newstatus == 'Yes' else 3 + StudentComplain.objects.filter(id=cid).update(status=intstatus, comment=comment) + + # Send notification to the complainer + try: + complainer_details = StudentComplain.objects.select_related('complainer').get(id=cid) + student = 0 + message = "Congrats! Your complaint has been resolved" + complaint_system_notif(request.user, complainer_details.complainer.user, 'comp_resolved_alert', complainer_details.id, student, message) + return Response({'success': 'Complaint status updated'}) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) + def get(self, request, cid): + """ + Returns the details of the complaint to be resolved. + """ + try: + complaint = StudentComplain.objects.select_related('complainer').get(id=cid) + serializer = StudentComplainSerializer(complaint) + return Response(serializer.data) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + +# Converted to DRF APIView +class SupervisorSubmitFeedbackView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request, complaint_id): + """ + Allows the supervisor to submit feedback for a complaint. + """ + serializer = FeedbackSerializer(data=request.data) + if serializer.is_valid(): + feedback = serializer.validated_data['feedback'] + rating = serializer.validated_data['rating'] + try: + rating = int(rating) + except ValueError: + return Response({'error': 'Invalid rating'}, status=status.HTTP_400_BAD_REQUEST) + StudentComplain.objects.filter(id=complaint_id).update(feedback=feedback, flag=rating) + + # Update caretaker's rating + try: + complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=complaint_id) + care = Caretaker.objects.filter(area=complaint.location).first() + rate = care.rating + newrate = int((rating + rate) / 2) if rate != 0 else rating + care.rating = newrate + care.save() + return Response({'success': 'Feedback submitted'}) + except Caretaker.DoesNotExist: + return Response({'error': 'Caretaker not found'}, status=status.HTTP_404_NOT_FOUND) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') + def get(self, request, complaint_id): + """ + Returns the complaint details for which feedback is to be submitted. + """ + try: + complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=complaint_id) + serializer = StudentComplainSerializer(complaint) + return Response(serializer.data) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) +# views.py - messages.success(request,message) - # return HttpResponseRedirect('/complaint/user') - - return HttpResponseRedirect('/complaint/supervisor') +# Import DRF classes +from rest_framework.views import APIView +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from rest_framework import status - else: - - - all_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').order_by('-id') - area = all_caretaker[0].area - - numtemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(location = area).filter(status = 0).count() - num = int(numtemp/2+0.5) - all_complaint = [] - user_details=User.objects.get(id=y.user_id) - +# Import necessary models and serializers +from .models import Caretaker, StudentComplain, Supervisor, Workers, SectionIncharge +from .serializers import StudentComplainSerializer, WorkersSerializer # Added WorkersSerializer +from applications.globals.models import User, ExtraInfo, HoldsDesignation - +# Converted 'removew' function to DRF APIView 'RemoveWorkerView' +class RemoveWorkerView(APIView): + permission_classes = [IsAuthenticated] - - current_user = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() - user_details=User.objects.get(id=y.user_id) - des=HoldsDesignation.objects.filter(user=user_details).all() - # print(y.user_id) - # print(user_details.username) - # print(des[0].user) - outbox_files = view_outbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" - ) + def post(self, request, work_id): + """ + Allows the caretaker to remove a worker if not assigned to any complaints. + """ + try: + worker = Workers.objects.get(id=work_id) + assigned_complaints = StudentComplain.objects.filter(worker_id=worker).count() + if assigned_complaints == 0: + worker.delete() + return Response({'success': 'Worker removed successfully'}, status=status.HTTP_200_OK) + else: + return Response({'error': 'Worker is assigned to some complaints'}, status=status.HTTP_400_BAD_REQUEST) + except Workers.DoesNotExist: + return Response({'error': 'Worker not found'}, status=status.HTTP_404_NOT_FOUND) + + # Optionally, accept DELETE method + def delete(self, request, work_id): + return self.post(request, work_id) + +# Converted 'assign_worker' function to DRF APIView 'AssignWorkerView' +class ForwardCompaintView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request, comp_id1): + """ + Assigns a complaint to a supervisor. + """ + current_user = request.user + y = ExtraInfo.objects.filter(user=current_user).first() + complaint_id = comp_id1 - outbox=[] - comp_list=set() - for i in outbox_files: - # print(i) - outbox.append(i) - - for i in outbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - comp_list.add(complaint) - # file_history = view_history(file_id=i['id']) - - # comp=File.objects.filter(uploader=file_history[0]['current_id']) - # for j in comp: - # c=StudentComplain.objects.all().filter(id=j.src_object_id) - # comp_list.add(c) - # print(c[0]) - - # break - complaint_final_list=[] - for i in comp_list: - complaint_final_list.append(i[0]) - sorted_history_out = sorted(complaint_final_list, key=attrgetter('complaint_date'), reverse=True) - - inbox_files = view_inbox( - username=user_details.username, - designation=des[0].designation, - src_module="complaint" + try: + complaint = StudentComplain.objects.get(id=complaint_id) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + + complaint_type = complaint.complaint_type + + supervisors = Supervisor.objects.filter(type=complaint_type) + if not supervisors.exists(): + return Response({'error': 'Supervisor does not exist for this complaint type'}, status=status.HTTP_404_NOT_FOUND) + + supervisor = supervisors.first() + supervisor_details = ExtraInfo.objects.get(id=supervisor.sup_id.id) + + # Update complaint status + complaint.status = 1 + complaint.save() + + # Forward file to supervisor + sup_designations = HoldsDesignation.objects.filter(user=supervisor_details.user_id) + + files = File.objects.filter(src_object_id=complaint_id) + + if not files.exists(): + return Response({'error': 'No files associated with this complaint'}, status=status.HTTP_206_PARTIAL_CONTENT) + + supervisor_username = User.objects.get(id=supervisor_details.user_id).username + + file = forward_file( + file_id=files.first().id, + receiver=supervisor_username, + receiver_designation=sup_designations.first().designation, + file_extra_JSON={}, + remarks="", + file_attachment=None ) - inbox=[] - comp_list_in=set() - for i in inbox_files: - inbox.append(i) - # print(inbox[0]['id']) - - for i in inbox: - file_history = view_history(file_id=i['id']) - print(i['id']) - comp=File.objects.filter(id=i['id']) - print(comp[0].src_object_id) - complaint=StudentComplain.objects.all().filter(id=comp[0].src_object_id) - print(complaint) - comp_list_in.add(complaint) - # print(complaint[0]) - # for j in comp: - # c=StudentComplain.objects.all().filter(id=j.src_object_id) - # comp_list_in.add(c) - # print(c[0]) - - # break - complaint_final_list_in=[] - for i in comp_list_in: - complaint_final_list_in.append(i[0]) - - sorted_history = sorted(complaint_final_list_in, key=attrgetter('complaint_date'), reverse=True) - print(complaint_final_list_in) - return render(request, "complaintModule/supervisor1.html", - - {'history':sorted_history,'all_caretaker': all_caretaker, 'all_complaint': all_complaint,'outbox':sorted_history_out}) - -@login_required -def caretaker_id_know_more(request,caretaker_id): - this_caretaker = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').get(id = caretaker_id) - this_caretaker_area = this_caretaker.area - list_pending_complaints = [] - list_pending_complaintstemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(location = this_caretaker_area).filter(status = 0) - j = 1 - for i in list_pending_complaintstemp: - list_pending_complaints.append(i) - - num = len(list_pending_complaints) - return render(request, "complaintModule/caretaker_id_know_more.html",{'this_caretaker':this_caretaker , 'list_pending_complaints':list_pending_complaints, 'num':num}) + return Response({'success': 'Complaint assigned to supervisor'}, status=status.HTTP_200_OK) + def get(self, request, comp_id1): + """ + Retrieves complaint details. + """ + try: + complaint = StudentComplain.objects.get(id=comp_id1) + serializer = StudentComplainSerializer(complaint) + return Response(serializer.data, status=status.HTTP_200_OK) + except StudentComplain.DoesNotExist: + return Response({'error': 'Not a valid complaint'}, status=status.HTTP_404_NOT_FOUND) -def search_complaint(request): - return HttpResponseRedirect('/login/') +# Converted 'deletecomplaint' function to DRF APIView 'DeleteComplaintView' +class DeleteComplaintView(APIView): + permission_classes = [IsAuthenticated] -@login_required -def resolvepending(request, cid): - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - thiscomplaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - if request.method == 'POST': - newstatus = request.POST.get('yesorno','') - comment = request.POST.get('comment') - intstatus = 0 - if newstatus == 'Yes': - intstatus = 2 - else: - intstatus = 3 - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(status=intstatus) - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(comment=comment) - complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - student=0 - message = "Congrats! Your complaint has been resolved" - complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert',complainer_details.id,student,message) - return HttpResponseRedirect("/complaint/caretaker/") - else: - # complainer_details = StudentComplain.objects.get(id=cid) - # complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert') - return render(request,"complaintModule/resolve_pending.html",{"a" : a,"thiscomplaint" : thiscomplaint}) - - - - -@login_required -def resolvependingsuper(request, cid): - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - thiscomplaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=cid) - if request.method == 'POST': - newstatus = request.POST.get('yesorno','') - comment = request.POST.get('comment') - intstatus = 0 - if newstatus == 'Yes': - intstatus = 2 - else: - intstatus = 3 - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=cid).\ - update(status=intstatus) - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(id=cid).\ - update(comment=comment) - complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').get(id=cid) - student=0 - message = "Congrats! Your complaint has been resolved" - complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert',complainer_details.id,student,message) - return HttpResponseRedirect("/complaint/supervisor/") - else: - # complainer_details = StudentComplain.objects.get(id=cid) - # complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert') - return render(request,"complaintModule/resolve_pending.html",{"a" : a,"thiscomplaint" : thiscomplaint}) - - - - -@login_required -def resolvependingsuper(request, cid): - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - thiscomplaint = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - if request.method == 'POST': - newstatus = request.POST.get('yesorno','') - comment = request.POST.get('comment') - intstatus = 0 - if newstatus == 'Yes': - intstatus = 2 - else: - intstatus = 3 - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(status=intstatus) - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=cid).\ - update(comment=comment) - complainer_details = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=cid) - student=0 - message = "Congrats! Your complaint has been resolved" - complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert',complainer_details.id,student,message) - return HttpResponseRedirect("/complaint/supervisor/") - else: - # complainer_details = StudentComplain.objects.get(id=cid) - # complaint_system_notif(request.user, complainer_details.complainer.user ,'comp_resolved_alert') - return render(request,"complaintModule/resolve_pending.html",{"a" : a,"thiscomplaint" : thiscomplaint}) - - - - -def login1(request): - if request.method == 'POST': - u = request.POST.get('username', '') - p = request.POST.get('password', '') - user = authenticate(username=u, password=p) - if user is not None: - if user.is_active: - login(request, user) - a = User.objects.get(username=u) - b = ExtraInfo.objects.all().select_related('user','department').get(user=a) - return HttpResponseRedirect('/complaint/') - else: - return HttpResponse("

wrong user credentials

") - else: - return HttpResponseRedirect('/login/') - -@login_required -def feedback_super(request, feedcomp_id): - detail3 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=feedcomp_id) - a=User.objects.get(username=detail3.complainer.user.username) - y=ExtraInfo.objects.all().select_related('user','department').get(user=a) - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() - comp_id=temp.id - loc = detail3.location - care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=loc).first() - return render(request, "complaintModule/feedback_super.html", {"detail3": detail3,"comp_id":comp_id,"care":care}) - - -@login_required -def feedback_care(request, feedcomp_id): - detail2 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=feedcomp_id) - a=User.objects.get(username=detail2.complainer.user.username) - y=ExtraInfo.objects.all().select_related('user','department').get(user=a) - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() - comp_id=temp.id - return render(request, "complaintModule/feedback_care.html", {"detail2": detail2,"comp_id":comp_id}) - - -#for complainaint and caretaker -@login_required -def detail(request, detailcomp_id1): - """ - function that shows detail about complaint - """ - detail = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=detailcomp_id1) - if(detail.worker_id is None): - worker_name = None - worker_id = detail.worker_id - else: - worker_id = detail.worker_id.id - worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=worker_id) - worker_name = worker.name - a=User.objects.get(username=detail.complainer.user.username) - y=ExtraInfo.objects.all().select_related('user','department').get(user=a) - num=0 - if detail.upload_complaint != "": - num = 1 - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() - comp_id=temp.id - return render(request, "complaintModule/complaint_user_detail.html", {"detail": detail, "comp_id":detail.id,"num":num,"worker_name":worker_name}) - - - -#for SectionIncharge -@login_required -def detail2(request, detailcomp_id1): - detail2 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=detailcomp_id1) - if(detail2.worker_id is None): - worker_name = None - worker_id = detail2.worker_id - else: - worker_id = detail2.worker_id.id - worker = Workers.objects.select_related('secincharge_id','secincharge_id__staff_id','secincharge_id__staff_id__user','secincharge_id__staff_id__department').get(id=worker_id) - worker_name = worker.name - a=User.objects.get(username=detail2.complainer.user.username) - y=ExtraInfo.objects.all().select_related('user','department').get(user=a) - num=0 - - if detail2.upload_complaint != "": - num = 1 - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() - comp_id=temp.id - return render(request, "complaintModule/complaint_secincharge_detail.html", {"detail2": detail2, "comp_id":detail2.id,"num":num,"worker_name":worker_name,"wid":worker_id}) - - -@login_required -def detail3(request, detailcomp_id1): - detail3 = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=detailcomp_id1) - a=User.objects.get(username=detail3.complainer.user.username) - y=ExtraInfo.objects.all().select_related('user','department').get(user=a) - num=0 - if detail3.upload_complaint != "": - num = 1 - temp=StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(complainer=y).first() - comp_id=temp.id - loc = detail3.location - care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=loc).first() - return render(request, "complaintModule/complaint_supervisor_detail.html", {"detail3": detail3,"comp_id":comp_id,"care":care,"num":num}) - - - - -@login_required - -def supervisorlodge(request): - """ - The function is used to register a complaint - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - num = 1 - comp_id = y.id - if request.method == 'POST': - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type - complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': - complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': - complaint_finish = datetime.now() + timedelta(days=3) - y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - # x = StudentComplain(complainer=y, - # complaint_type=comp_type, - # location=location, - # specific_location=specific_location, - # details=details, - # status=status, - # complaint_finish=complaint_finish, - # upload_complaint=comp_file) - - - # x.save() - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history = [] - j = 1 - k = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - - for h in history: - h.serial_no = k - k = k+1 - # if location == "hall1": - # dsgn = "hall1caretaker" - # elif location == "hall3": - # dsgn = "hall3caretaker" - # else : - # dsgn = "hall4caretaker" - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" - else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - - - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') - - messages.success(request,message) - return HttpResponseRedirect('/complaint/supervisor') - - else: - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history=[] - - notification = Notification.objects.filter(recipient=a.id) - notification = notification.filter(data__exact={'url':'complaint:detail','module':'Complaint System'}) - # notification_message = [] - # for notification in x: - # to = User.objects.get(id=notification.actor_object_id).username - # from django.utils.timesince import timesince as timesince_ - # duration = timesince_(notification.timestamp,None) - # notification_message.append(notification.verb+' by '+ to + ' ' + duration + ' ago ') - + def post(self, request, comp_id1): + """ + Deletes a complaint. + """ + try: + complaint = StudentComplain.objects.get(id=comp_id1) + complaint.delete() + return Response({'success': 'Complaint deleted successfully'}, status=status.HTTP_200_OK) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + def delete(self, request, comp_id1): + return self.post(request, comp_id1) +# Converted 'changestatus' function to DRF APIView 'ChangeStatusView' +class ChangeStatusView(APIView): + permission_classes = [IsAuthenticated] - j = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - for i in history: - i.serial_no = j - j = j+1 - - # if location == "hall-1": - # dsgn ="hall1caretaker" - # elif location =="hall-3": - # dsgn ="hall3caretaker" - # elif location =="hall-4": - # dsgn ="hall4caretaker" - # elif location =="CC1": - # dsgn ="CC convenor" - # elif location =="CC2": - # dsgn ="CC2 convener" - # elif location == "core_lab": - # dsgn = "corelabcaretaker" - # elif location =="LHTC": - # dsgn ="lhtccaretaker" - # elif location =="NR2": - # dsgn ="nr2caretaker" - # else: - # dsgn = "rewacaretaker" - # caretaker_name = HoldsDesignation.objects.get(designation__name = dsgn) - - # complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert') - return render(request, "complaintModule/supervisor1.html", - {'history': history,'notification':notification, 'comp_id': y.id}) - - return render(request, "complaintModule/complaint_user.html", - {'history': history, 'comp_id': comp_id }) - - - - -@login_required -def submitfeedbacksuper(request, complaint_id): - """ - The function is used by the complainant to enter feedback after the complaint has been resolved - @param: - request - trivial. - complaint_id - id of the registerd complaint. - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - - if request.method == 'POST': - feedback = request.POST.get('feedback', '') - rating = request.POST.get('rating', '') - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(feedback=feedback, flag=rating) - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).first() - care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).first() - rate = care.rating - newrate = 0 - if rate == 0: - newrate = rating - else: - a1 = int(rating) - b1 = int(rate) - c1 = int((a1+b1)/2) - newrate = c1 - - Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).update(rating=newrate) - return HttpResponseRedirect('/complaint/supervisor/') - return render(request,"complaintModule/feedback.html",{'a' : a}) - - else: - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=complaint_id) - return render(request, "complaintModule/submit_feedback.html", {'a': a}) - - - -@login_required - -def caretakerlodge(request): - """ - The function is used to register a complaint - @param: - request - trivial. - - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - num = 1 - comp_id = y.id - if request.method == 'POST': - comp_type = request.POST.get('complaint_type', '') - location = request.POST.get('Location', '') - specific_location = request.POST.get('specific_location', '') - comp_file = request.FILES.get('myfile') - - details = request.POST.get('details', '') - status = 0 - # finish time is according to complaint type - complaint_finish = datetime.now() + timedelta(days=2) - if comp_type == 'Electricity': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'carpenter': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'plumber': - complaint_finish = datetime.now() + timedelta(days=2) - elif comp_type == 'garbage': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'dustbin': - complaint_finish = datetime.now() + timedelta(days=1) - elif comp_type == 'internet': - complaint_finish = datetime.now() + timedelta(days=4) - elif comp_type == 'other': - complaint_finish = datetime.now() + timedelta(days=3) - y = ExtraInfo.objects.all().select_related('user','department').get(id=comp_id) - #check if location given - if location!="": - # x = StudentComplain(complainer=y, - # complaint_type=comp_type, - # location=location, - # specific_location=specific_location, - # details=details, - # status=status, - # complaint_finish=complaint_finish, - # upload_complaint=comp_file) - - - # x.save() - obj1, created = StudentComplain.objects.get_or_create(complainer=y, - complaint_type=comp_type, - location=location, - specific_location=specific_location, - details=details, - status=status, - complaint_finish=complaint_finish, - upload_complaint=comp_file) - - - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history = [] - j = 1 - k = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - - for h in history: - h.serial_no = k - k = k+1 - # if location == "hall1": - # dsgn = "hall1caretaker" - # elif location == "hall3": - # dsgn = "hall3caretaker" - # else : - # dsgn = "hall4caretaker" - if location == "hall-1": - dsgn ="hall1caretaker" - elif location =="hall-3": - dsgn ="hall3caretaker" - elif location =="hall-4": - dsgn ="hall4caretaker" - elif location =="CC1": - dsgn ="cc1convener" - elif location =="CC2": - dsgn ="CC2 convener" - elif location == "core_lab": - dsgn = "corelabcaretaker" - elif location =="LHTC": - dsgn ="lhtccaretaker" - elif location =="NR2": - dsgn ="nr2caretaker" - elif location =="Maa Saraswati Hostel": - dsgn ="mshcaretaker" - elif location =="Nagarjun Hostel": - dsgn ="nhcaretaker" - elif location =="Panini Hostel": - dsgn ="phcaretaker" - else: - dsgn = "rewacaretaker" - caretaker_name = HoldsDesignation.objects.select_related('user','working','designation').get(designation__name = dsgn) - - - # This is to allow the student - student = 1 - message = "A New Complaint has been lodged" - complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert',obj1.id,student,message) - - # return render(request, "complaintModule/complaint_user.html", - # {'history': history, 'comp_id': comp_id }) - # next = request.POST.get('next', '/') - - messages.success(request,message) - return HttpResponseRedirect('/complaint/caretaker') - - else: - a = get_object_or_404(User, username=request.user.username) - y = ExtraInfo.objects.all().select_related('user','department').filter(user=a).first() - historytemp = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department','worker_id','worker_id__caretaker_id__staff_id','worker_id__caretaker_id__staff_id__user','worker_id__caretaker_id__staff_id__department').filter(complainer=y).order_by('-id') - history=[] - - notification = Notification.objects.filter(recipient=a.id) - notification = notification.filter(data__exact={'url':'complaint:detail','module':'Complaint System'}) - # notification_message = [] - # for notification in x: - # to = User.objects.get(id=notification.actor_object_id).username - # from django.utils.timesince import timesince as timesince_ - # duration = timesince_(notification.timestamp,None) - # notification_message.append(notification.verb+' by '+ to + ' ' + duration + ' ago ') + def post(self, request, complaint_id, status): + """ + Allows the caretaker to change the status of a complaint. + """ + try: + complaint = StudentComplain.objects.get(id=complaint_id) + if status == '3' or status == '2': + complaint.status = status + complaint.worker_id = None + else: + complaint.status = status + complaint.save() + return Response({'success': 'Complaint status updated'}, status=status.HTTP_200_OK) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + +# Converted 'changestatussuper' function to DRF APIView 'ChangeStatusSuperView' +class ChangeStatusSuperView(APIView): + permission_classes = [IsAuthenticated] + + def post(self, request, complaint_id, status): + """ + Allows the supervisor to change the status of a complaint. + """ + try: + complaint = StudentComplain.objects.get(id=complaint_id) + if status == '3' or status == '2': + complaint.status = status + complaint.worker_id = None + else: + complaint.status = status + complaint.save() + return Response({'success': 'Complaint status updated'}, status=status.HTTP_200_OK) + except StudentComplain.DoesNotExist: + return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) +class GenerateReportView(APIView): + permission_classes = [IsAuthenticated] + def get(self, request): + """ + Generates a report of complaints for the caretaker's area, warden's area, or supervisor's type. + """ + user = request.user + is_caretaker = hasattr(user, 'caretaker') + is_supervisor = False + is_warden = hasattr(user, 'warden') - j = 1 - for i in historytemp: - history.append(i) - # if j%2 != 0: - # history.append(i) - # j = j+1 - - for i in history: - i.serial_no = j - j = j+1 - - # if location == "hall-1": - # dsgn ="hall1caretaker" - # elif location =="hall-3": - # dsgn ="hall3caretaker" - # elif location =="hall-4": - # dsgn ="hall4caretaker" - # elif location =="CC1": - # dsgn ="CC convenor" - # elif location =="CC2": - # dsgn ="CC2 convener" - # elif location == "core_lab": - # dsgn = "corelabcaretaker" - # elif location =="LHTC": - # dsgn ="lhtccaretaker" - # elif location =="NR2": - # dsgn ="nr2caretaker" - # else: - # dsgn = "rewacaretaker" - # caretaker_name = HoldsDesignation.objects.get(designation__name = dsgn) - - # complaint_system_notif(request.user, caretaker_name.user,'lodge_comp_alert') - return render(request, "complaintModule/complaint_caretaker.html", - {'history': history,'notification':notification, 'comp_id': y.id}) - - return render(request, "complaintModule/complaint_user.html", - {'history': history, 'comp_id': comp_id }) - - -@login_required -def submitfeedbackcaretaker(request, complaint_id): - """ - The function is used by the complainant to enter feedback after the complaint has been resolved - @param: - request - trivial. - complaint_id - id of the registerd complaint. - - @variables: - issue - The issue object. - supported - True if the user's intention is to support the issue. - support_count - Total supporters of the above issue. - context - Holds data needed to make necessary changes in the template. - """ - - if request.method == 'POST': - feedback = request.POST.get('feedback', '') - rating = request.POST.get('rating', '') - StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).\ - update(feedback=feedback, flag=rating) - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').filter(id=complaint_id).first() - care = Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).first() - rate = care.rating - newrate = 0 - if rate == 0: - newrate = rating - else: - a1 = int(rating) - b1 = int(rate) - c1 = int((a1+b1)/2) - newrate = c1 - - Caretaker.objects.select_related('staff_id','staff_id__user','staff_id__department').filter(area=a.location).update(rating=newrate) - return HttpResponseRedirect('/complaint/caretaker/') - return render(request,"complaintModule/feedback.html",{'a' : a}) - - else: - a = StudentComplain.objects.select_related('complainer','complainer__user','complainer__department').get(id=complaint_id) - return render(request, "complaintModule/submit_feedback.html", {'a': a}) \ No newline at end of file + # Check if user is a supervisor + try: + supervisor = Supervisor.objects.get(sup_id=user.extrainfo) + is_supervisor = True + except Supervisor.DoesNotExist: + is_supervisor = False + + if not is_caretaker and not is_supervisor and not is_warden: + return Response({"detail": "Not authorized to generate report."}, status=403) + + complaints = None + + # Generate report for supervisor + if is_supervisor: + print(f"Generating report for Supervisor {supervisor}") + complaints = StudentComplain.objects.filter(complaint_type=supervisor.type) + + # Generate report for caretaker + if is_caretaker and not is_supervisor: + caretaker = get_object_or_404(Caretaker, staff_id=user.extrainfo) + complaints = StudentComplain.objects.filter(location=caretaker.area) + + # if is_warden: + # warden = get_object_or_404(Warden, staff_id=user.extrainfo) + # if complaints: + # complaints = complaints.filter(location=warden.area) + # else: + # complaints = StudentComplain.objects.filter(location=warden.area) + + # Serialize and return the complaints + serializer = StudentComplainSerializer(complaints, many=True) + return Response(serializer.data) From b4af1fa3b15e203d541904c5b716392687d52178 Mon Sep 17 00:00:00 2001 From: Prit Bhanushali Date: Thu, 20 Feb 2025 22:39:01 +0530 Subject: [PATCH 2/9] Added service provider, service authority and removed the supervisor --- .../applications/complaint_system/admin.py | 4 +- .../complaint_system/api/serializers.py | 6 +- .../applications/complaint_system/api/urls.py | 8 +- .../complaint_system/api/views.py | 32 ++--- .../migrations/0001_initial.py | 12 +- .../applications/complaint_system/models.py | 28 ++++- .../static/complaint_system/js/rating.js | 2 +- .../applications/complaint_system/urls.py | 30 ++--- .../applications/complaint_system/views.py | 110 +++++++++--------- 9 files changed, 134 insertions(+), 98 deletions(-) diff --git a/FusionIIIT/applications/complaint_system/admin.py b/FusionIIIT/applications/complaint_system/admin.py index 8bf43cab7..631892e13 100644 --- a/FusionIIIT/applications/complaint_system/admin.py +++ b/FusionIIIT/applications/complaint_system/admin.py @@ -1,9 +1,9 @@ from django.contrib import admin -from .models import Caretaker, StudentComplain, Supervisor, Workers, SectionIncharge +from .models import Caretaker, StudentComplain, ServiceProvider, Workers, SectionIncharge admin.site.register(Caretaker) admin.site.register(Workers) admin.site.register(StudentComplain) -admin.site.register(Supervisor) +admin.site.register(ServiceProvider) admin.site.register(SectionIncharge) diff --git a/FusionIIIT/applications/complaint_system/api/serializers.py b/FusionIIIT/applications/complaint_system/api/serializers.py index 8a2b97439..f31ee29b2 100644 --- a/FusionIIIT/applications/complaint_system/api/serializers.py +++ b/FusionIIIT/applications/complaint_system/api/serializers.py @@ -2,7 +2,7 @@ from rest_framework.authtoken.models import Token from rest_framework import serializers from notifications.models import Notification -from applications.complaint_system.models import Caretaker, StudentComplain, Supervisor, Workers +from applications.complaint_system.models import Caretaker, StudentComplain, ServiceProvider, Workers from applications.globals.models import ExtraInfo,User class StudentComplainSerializers(serializers.ModelSerializer): @@ -21,9 +21,9 @@ class Meta: model = Caretaker fields=('__all__') -class SupervisorSerializers(serializers.ModelSerializer): +class ServiceProviderSerializers(serializers.ModelSerializer): class Meta: - model=Supervisor + model=ServiceProvider fields=('__all__') class ExtraInfoSerializers(serializers.ModelSerializer): diff --git a/FusionIIIT/applications/complaint_system/api/urls.py b/FusionIIIT/applications/complaint_system/api/urls.py index 5d7cacd0b..9ad3df493 100644 --- a/FusionIIIT/applications/complaint_system/api/urls.py +++ b/FusionIIIT/applications/complaint_system/api/urls.py @@ -21,9 +21,9 @@ url(r'^removecaretaker/(?P[0-9]+)',views.edit_caretaker_api,name='caretaker-delete-api'), url(r'^updatecaretaker/(?P[0-9]+)',views.edit_caretaker_api,name='caretaker-put-api'), - url(r'^supervisors',views.supervisor_api,name='supervisor-get-api'), - url(r'^addsupervisor',views.supervisor_api,name='supervisor-post-api'), - url(r'^removesupervisor/(?P[0-9]+)',views.edit_supervisor_api,name='supervisor-delete-api'), - url(r'^updatesupervisor/(?P[0-9]+)',views.edit_supervisor_api,name='supervisor-put-api'), + url(r'^service_providers',views.service_provider_api,name='service_provider-get-api'), + url(r'^addservice_provider',views.service_provider_api,name='service_provider-post-api'), + url(r'^removeservice_provider/(?P[0-9]+)',views.edit_service_provider_api,name='service_provider-delete-api'), + url(r'^updateservice_provider/(?P[0-9]+)',views.edit_service_provider_api,name='service_provider-put-api'), ] \ No newline at end of file diff --git a/FusionIIIT/applications/complaint_system/api/views.py b/FusionIIIT/applications/complaint_system/api/views.py index c12b73ddb..1d4aaa400 100644 --- a/FusionIIIT/applications/complaint_system/api/views.py +++ b/FusionIIIT/applications/complaint_system/api/views.py @@ -10,7 +10,7 @@ from rest_framework.permissions import AllowAny from rest_framework.response import Response from applications.globals.models import User,ExtraInfo -from applications.complaint_system.models import Caretaker, StudentComplain, Supervisor, Workers +from applications.complaint_system.models import Caretaker, StudentComplain, ServiceProvider, Workers from . import serializers @@ -51,7 +51,7 @@ def student_complain_api(request): complain = StudentComplain.objects.filter(location = staff.area) elif user.user_type == 'faculty': faculty = ExtraInfo.objects.get(id=user.id) - faculty = Supervisor.objects.get(sup_id=faculty) + faculty = ServiceProvider.objects.get(ser_pro_id=faculty) complain = StudentComplain.objects.filter(location = faculty.area) complains = serializers.StudentComplainSerializers(complain,many=True).data resp = { @@ -154,8 +154,8 @@ def caretaker_api(request): user = get_object_or_404(User ,username=request.user.username) user = ExtraInfo.objects.all().filter(user = user).first() try : - supervisor = Supervisor.objects.get(staff_id=user) - except Supervisor.DoesNotExist: + service_provider = ServiceProvider.objects.get(staff_id=user) + except ServiceProvider.DoesNotExist: return Response({'message':'Logged in user does not have the permissions'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) serializer = serializers.CaretakerSerializers(data=request.data) if serializer.is_valid(): @@ -170,8 +170,8 @@ def edit_caretaker_api(request,c_id): user = get_object_or_404(User ,username=request.user.username) user = ExtraInfo.objects.all().filter(user = user).first() try : - supervisor = Supervisor.objects.get(staff_id=user) - except Supervisor.DoesNotExist: + service_provider = ServiceProvider.objects.get(staff_id=user) + except ServiceProvider.DoesNotExist: return Response({'message':'Logged in user does not have the permissions'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) try: caretaker = Caretaker.objects.get(id = c_id) @@ -190,13 +190,13 @@ def edit_caretaker_api(request,c_id): @api_view(['GET','POST']) @permission_classes([IsAuthenticated]) @authentication_classes([TokenAuthentication]) -def supervisor_api(request): +def service_provider_api(request): if request.method == 'GET': - supervisor = Supervisor.objects.all() - supervisors = serializers.SupervisorSerializers(supervisor,many=True).data + service_provider = ServiceProvider.objects.all() + service_providers = serializers.ServiceProviderSerializers(service_provider,many=True).data resp = { - 'supervisors' : supervisors, + 'service_providers' : service_providers, } return Response(data=resp,status=status.HTTP_200_OK) @@ -204,7 +204,7 @@ def supervisor_api(request): user = get_object_or_404(User,username=request.user.username) if user.is_superuser == False: return Response({'message':'Logged in user does not have permission'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) - serializer = serializers.SupervisorSerializers(data=request.data) + serializer = serializers.ServiceProviderSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) @@ -213,19 +213,19 @@ def supervisor_api(request): @api_view(['DELETE','PUT']) @permission_classes([IsAuthenticated]) @authentication_classes([TokenAuthentication]) -def edit_supervisor_api(request,s_id): +def edit_service_provider_api(request,s_id): user = get_object_or_404(User,username=request.user.username) if user.is_superuser == False: return Response({'message':'Logged in user does not have permission'},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION) try: - supervisor = Supervisor.objects.get(id = s_id) - except Supervisor.DoesNotExist: + service_provider = ServiceProvider.objects.get(id = s_id) + except ServiceProvider.DoesNotExist: return Response({'message': 'The Caretaker does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'DELETE': - supervisor.delete() + service_provider.delete() return Response({'message': 'Caretaker deleted'},status=status.HTTP_404_NOT_FOUND) elif request.method == 'PUT': - serializer = serializers.SupervisorSerializers(supervisor,data=request.data) + serializer = serializers.ServiceProviderSerializers(service_provider,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) diff --git a/FusionIIIT/applications/complaint_system/migrations/0001_initial.py b/FusionIIIT/applications/complaint_system/migrations/0001_initial.py index e40ba5606..fea1b5a5a 100644 --- a/FusionIIIT/applications/complaint_system/migrations/0001_initial.py +++ b/FusionIIIT/applications/complaint_system/migrations/0001_initial.py @@ -34,11 +34,19 @@ class Migration(migrations.Migration): ], ), migrations.CreateModel( - name='Supervisor', + name='ServiceProvider', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='Electricity', max_length=30)), - ('sup_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), + ('ser_pro_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), + ], + ), + migrations.CreateModel( + name='ServiceAuthority', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='Electricity', max_length=30)), + ('ser_auth_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), ], ), migrations.CreateModel( diff --git a/FusionIIIT/applications/complaint_system/models.py b/FusionIIIT/applications/complaint_system/models.py index 47145fad3..630152bf6 100644 --- a/FusionIIIT/applications/complaint_system/models.py +++ b/FusionIIIT/applications/complaint_system/models.py @@ -89,9 +89,31 @@ def __str__(self): return str(self.complainer.user.username) -class Supervisor(models.Model): - sup_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) +class ServiceProvider(models.Model): + ser_pro_id = models.ForeignKey( + ExtraInfo, + on_delete=models.CASCADE, + db_column="ser_pro_id_id" # Map to the existing column + ) type = models.CharField(choices=Constants.COMPLAINT_TYPE, max_length=30,default='Electricity') + class Meta: + db_table = "complaint_system_service_provider" + + def __str__(self): + return str(self.ser_pro_id) + '-' + str(self.type) + + +class ServiceAuthority(models.Model): + ser_pro_id = models.ForeignKey( + ExtraInfo, + on_delete=models.CASCADE, + db_column="ser_auth_id_id" # Map to the existing column + ) + type = models.CharField(choices=Constants.COMPLAINT_TYPE, max_length=30,default='Electricity') + + class Meta: + db_table = "complaint_system_service_authority" + def __str__(self): - return str(self.sup_id) + '-' + str(self.type) + return str(self.ser_pro_id) + '-' + str(self.type) diff --git a/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js b/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js index 825fe759d..56ac096de 100644 --- a/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js +++ b/FusionIIIT/applications/complaint_system/static/complaint_system/js/rating.js @@ -130,7 +130,7 @@ $(document).ready(function(){ // alert("Complaint successfully lodged"); setTimeout(function() { - window.location.replace('http://localhost:8000/complaint/supervisor'); + window.location.replace('http://localhost:8000/complaint/service_provider'); }, 1500); diff --git a/FusionIIIT/applications/complaint_system/urls.py b/FusionIIIT/applications/complaint_system/urls.py index c39a5d965..c61e4382a 100644 --- a/FusionIIIT/applications/complaint_system/urls.py +++ b/FusionIIIT/applications/complaint_system/urls.py @@ -19,13 +19,13 @@ SubmitFeedbackCaretakerView, ) from .views import ( - SupervisorLodgeView, - SupervisorView, + ServiceProviderLodgeView, + ServiceProviderView, FeedbackSuperView, CaretakerIdKnowMoreView, - SupervisorComplaintDetailView, - SupervisorResolvePendingView, - SupervisorSubmitFeedbackView, + ServiceProviderComplaintDetailView, + ServiceProviderResolvePendingView, + ServiceProviderSubmitFeedbackView, ) from django.urls import path @@ -57,22 +57,22 @@ path('caretaker/detail2//', ComplaintDetailView.as_view()), # Converted to DRF path('caretaker/search_complaint', SearchComplaintView.as_view()), # Converted to DRF path('caretaker//feedback/', SubmitFeedbackCaretakerView.as_view()), # Converted to DRF - # Supervisor URLs - path('supervisor/lodge/', SupervisorLodgeView.as_view()), - path('supervisor/', SupervisorView.as_view()), - path('supervisor/feedback//', FeedbackSuperView.as_view()), - path('supervisor/caretaker_id_know_more//', CaretakerIdKnowMoreView.as_view()), + # ServiceProvider URLs + path('service_provider/lodge/', ServiceProviderLodgeView.as_view()), + path('service_provider/', ServiceProviderView.as_view()), + path('service_provider/feedback//', FeedbackSuperView.as_view()), + path('service_provider/caretaker_id_know_more//', CaretakerIdKnowMoreView.as_view()), # The following URL is commented out as per the original code - # path('supervisor/caretaker_id_know_more//complaint_reassign_super//', views.complaint_reassign_super, name='complaint_reassign_super'), - path('supervisor/detail//', SupervisorComplaintDetailView.as_view(), name='detail3'), - path('supervisor/pending//', SupervisorResolvePendingView.as_view()), - path('supervisor//', SupervisorSubmitFeedbackView.as_view()), + # path('service_provider/caretaker_id_know_more//complaint_reassign_super//', views.complaint_reassign_super, name='complaint_reassign_super'), + path('service_provider/detail//', ServiceProviderComplaintDetailView.as_view(), name='detail3'), + path('service_provider/pending//', ServiceProviderResolvePendingView.as_view()), + path('service_provider//', ServiceProviderSubmitFeedbackView.as_view()), # CRUD task URLs path('caretaker/worker_id_know_more//removew/', RemoveWorkerView.as_view()), path('caretaker//', ForwardCompaintView.as_view(), name='assign_worker'), path('caretaker/deletecomplaint//', DeleteComplaintView.as_view()), path('caretaker///', ChangeStatusView.as_view()), - path('supervisor///', ChangeStatusSuperView.as_view()), + path('service_provider///', ChangeStatusSuperView.as_view()), path('generate-report/', GenerateReportView.as_view(), name='generate-report-api'), ] \ No newline at end of file diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index da1ee656a..acef0c72c 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -8,7 +8,7 @@ from applications.globals.models import User, ExtraInfo, HoldsDesignation from notifications.models import Notification -from .models import Caretaker, StudentComplain, Supervisor +from .models import Caretaker, StudentComplain, ServiceProvider, ServiceAuthority from notification.views import complaint_system_notif from applications.filetracking.sdk.methods import * @@ -37,20 +37,20 @@ def get(self, request): """ a = request.user b = ExtraInfo.objects.select_related("user", "department").filter(user=a).first() - supervisor_list = Supervisor.objects.all() + service_provider_list = ServiceProvider.objects.all() caretaker_list = Caretaker.objects.all() - is_supervisor = False + is_service_provider = False is_caretaker = False - for i in supervisor_list: - if b.id == i.sup_id_id: - is_supervisor = True + for i in service_provider_list: + if b.id == i.ser_pro_id_id: + is_service_provider = True break for i in caretaker_list: if b.id == i.staff_id_id: is_caretaker = True break - if is_supervisor: - return Response({"user_type": "supervisor", "next_url": "/complaint/supervisor/"}) + if is_service_provider: + return Response({"user_type": "service_provider", "next_url": "/complaint/service_provider/"}) elif is_caretaker: return Response({"user_type": "caretaker", "next_url": "/complaint/caretaker/"}) elif b.user_type == "student": @@ -208,7 +208,7 @@ def get(self, request, detailcomp_id1): from django.shortcuts import get_object_or_404, render from applications.globals.models import User, ExtraInfo, HoldsDesignation from notifications.models import Notification -from .models import Caretaker, StudentComplain, Supervisor +from .models import Caretaker, StudentComplain, ServiceProvider from notification.views import complaint_system_notif from applications.filetracking.sdk.methods import * from applications.filetracking.models import * @@ -469,19 +469,19 @@ def get(self, request, complaint_id): from django.shortcuts import get_object_or_404, render from applications.globals.models import User, ExtraInfo, HoldsDesignation from notifications.models import Notification -from .models import Caretaker, StudentComplain, Supervisor +from .models import Caretaker, StudentComplain, ServiceProvider from notification.views import complaint_system_notif from applications.filetracking.sdk.methods import * from applications.filetracking.models import * from operator import attrgetter # Converted to DRF APIView -class SupervisorLodgeView(APIView): +class ServiceProviderLodgeView(APIView): permission_classes = [IsAuthenticated] def post(self, request): """ - Allows the supervisor to lodge a new complaint. + Allows the service_provider to lodge a new complaint. """ # Get the current user a = request.user @@ -553,7 +553,7 @@ def post(self, request): def get(self, request): """ - Returns the history of complaints lodged by the supervisor. + Returns the history of complaints lodged by the service_provider. """ a = request.user y = ExtraInfo.objects.select_related('user', 'department').filter(user=a).first() @@ -562,23 +562,23 @@ def get(self, request): return Response(serializer.data) # Converted to DRF APIView -class SupervisorView(APIView): +class ServiceProviderView(APIView): permission_classes = [IsAuthenticated] def get(self, request): """ - Returns the list of complaints assigned to the supervisor's area. + Returns the list of complaints assigned to the service_provider's area. """ current_user = request.user y = ExtraInfo.objects.select_related('user', 'department').filter(user=current_user).first() try: - supervisor = Supervisor.objects.select_related('sup_id').get(sup_id=y) - type = supervisor.type + service_provider = ServiceProvider.objects.select_related('ser_pro_id').get(ser_pro_id=y) + type = service_provider.type complaints = StudentComplain.objects.filter(complaint_type=type, status=1).order_by('-id') serializer = StudentComplainSerializer(complaints, many=True) return Response(serializer.data) - except Supervisor.DoesNotExist: - return Response({'error': 'Supervisor does not exist'}, status=status.HTTP_404_NOT_FOUND) + except ServiceProvider.DoesNotExist: + return Response({'error': 'ServiceProvider does not exist'}, status=status.HTTP_404_NOT_FOUND) # Converted to DRF APIView class FeedbackSuperView(APIView): @@ -586,7 +586,7 @@ class FeedbackSuperView(APIView): def get(self, request, feedcomp_id): """ - Returns the feedback details for a specific complaint for the supervisor. + Returns the feedback details for a specific complaint for the service_provider. """ try: complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=feedcomp_id) @@ -616,12 +616,12 @@ def get(self, request, caretaker_id): return Response({'error': 'Caretaker not found'}, status=status.HTTP_404_NOT_FOUND) # Converted to DRF APIView -class SupervisorComplaintDetailView(APIView): +class ServiceProviderComplaintDetailView(APIView): permission_classes = [IsAuthenticated] def get(self, request, detailcomp_id1): """ - Returns the details of a complaint for the supervisor, including caretaker info. + Returns the details of a complaint for the service_provider, including caretaker info. """ try: complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=detailcomp_id1) @@ -633,12 +633,12 @@ def get(self, request, detailcomp_id1): return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) # Converted to DRF APIView -class SupervisorResolvePendingView(APIView): +class ServiceProviderResolvePendingView(APIView): permission_classes = [IsAuthenticated] def post(self, request, cid): """ - Allows the supervisor to resolve a pending complaint. + Allows the service_provider to resolve a pending complaint. """ serializer = ResolvePendingSerializer(data=request.data) if serializer.is_valid(): @@ -671,12 +671,12 @@ def get(self, request, cid): return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) # Converted to DRF APIView -class SupervisorSubmitFeedbackView(APIView): +class ServiceProviderSubmitFeedbackView(APIView): permission_classes = [IsAuthenticated] def post(self, request, complaint_id): """ - Allows the supervisor to submit feedback for a complaint. + Allows the service_provider to submit feedback for a complaint. """ serializer = FeedbackSerializer(data=request.data) if serializer.is_valid(): @@ -721,7 +721,7 @@ def get(self, request, complaint_id): from rest_framework import status # Import necessary models and serializers -from .models import Caretaker, StudentComplain, Supervisor, Workers, SectionIncharge +from .models import Caretaker, StudentComplain, ServiceProvider, Workers, SectionIncharge from .serializers import StudentComplainSerializer, WorkersSerializer # Added WorkersSerializer from applications.globals.models import User, ExtraInfo, HoldsDesignation @@ -754,7 +754,7 @@ class ForwardCompaintView(APIView): def post(self, request, comp_id1): """ - Assigns a complaint to a supervisor. + Assigns a complaint to a service_provider. """ current_user = request.user y = ExtraInfo.objects.filter(user=current_user).first() @@ -767,37 +767,37 @@ def post(self, request, comp_id1): complaint_type = complaint.complaint_type - supervisors = Supervisor.objects.filter(type=complaint_type) - if not supervisors.exists(): - return Response({'error': 'Supervisor does not exist for this complaint type'}, status=status.HTTP_404_NOT_FOUND) + service_providers = ServiceProvider.objects.filter(type=complaint_type) + if not service_providers.exists(): + return Response({'error': 'ServiceProvider does not exist for this complaint type'}, status=status.HTTP_404_NOT_FOUND) - supervisor = supervisors.first() - supervisor_details = ExtraInfo.objects.get(id=supervisor.sup_id.id) + service_provider = service_providers.first() + service_provider_details = ExtraInfo.objects.get(id=service_provider.ser_pro_id.id) # Update complaint status complaint.status = 1 complaint.save() - # Forward file to supervisor - sup_designations = HoldsDesignation.objects.filter(user=supervisor_details.user_id) + # Forward file to service_provider + sup_designations = HoldsDesignation.objects.filter(user=service_provider_details.user_id) files = File.objects.filter(src_object_id=complaint_id) if not files.exists(): return Response({'error': 'No files associated with this complaint'}, status=status.HTTP_206_PARTIAL_CONTENT) - supervisor_username = User.objects.get(id=supervisor_details.user_id).username + service_provider_username = User.objects.get(id=service_provider_details.user_id).username file = forward_file( file_id=files.first().id, - receiver=supervisor_username, + receiver=service_provider_username, receiver_designation=sup_designations.first().designation, file_extra_JSON={}, remarks="", file_attachment=None ) - return Response({'success': 'Complaint assigned to supervisor'}, status=status.HTTP_200_OK) + return Response({'success': 'Complaint assigned to service_provider'}, status=status.HTTP_200_OK) def get(self, request, comp_id1): """ @@ -854,7 +854,7 @@ class ChangeStatusSuperView(APIView): def post(self, request, complaint_id, status): """ - Allows the supervisor to change the status of a complaint. + Allows the service_provider to change the status of a complaint. """ try: complaint = StudentComplain.objects.get(id=complaint_id) @@ -873,33 +873,39 @@ class GenerateReportView(APIView): def get(self, request): """ - Generates a report of complaints for the caretaker's area, warden's area, or supervisor's type. + Generates a report of complaints for the caretaker's area, warden's area, or service_provider's type. """ user = request.user is_caretaker = hasattr(user, 'caretaker') - is_supervisor = False + is_service_provider = False is_warden = hasattr(user, 'warden') - # Check if user is a supervisor + # Check if user is a service_provider try: - supervisor = Supervisor.objects.get(sup_id=user.extrainfo) - is_supervisor = True - except Supervisor.DoesNotExist: - is_supervisor = False + service_provider = ServiceProvider.objects.get(ser_pro_id=user.extrainfo) + is_service_provider = True + except ServiceProvider.DoesNotExist: + is_service_provider = False - if not is_caretaker and not is_supervisor and not is_warden: + try: + is_service_authority = ServiceAuthority.objects.get(ser_pro_id=user.extrainfo) + is_service_authority = True + except ServiceAuthority.DoesNotExist: + is_service_authority = False + + if not is_caretaker and not is_service_provider and not is_admin and not is_service_provider and not is_service_provider and not is_service_authority: return Response({"detail": "Not authorized to generate report."}, status=403) complaints = None - # Generate report for supervisor - if is_supervisor: - print(f"Generating report for Supervisor {supervisor}") - complaints = StudentComplain.objects.filter(complaint_type=supervisor.type) + # Generate report for service_provider + if is_service_provider: + print(f"Generating report for ServiceProvider {service_provider}") + complaints = StudentComplain.objects.filter(complaint_type=service_provider.type) # Generate report for caretaker - if is_caretaker and not is_supervisor: + if is_caretaker and not is_service_provider: caretaker = get_object_or_404(Caretaker, staff_id=user.extrainfo) complaints = StudentComplain.objects.filter(location=caretaker.area) From e905a5c204ce0c321b0e8f013f3499ebb10e1a3d Mon Sep 17 00:00:00 2001 From: Prit Bhanushali Date: Tue, 4 Mar 2025 15:32:50 +0530 Subject: [PATCH 3/9] Added New complaint lodged notification for caretaker --- .../applications/complaint_system/views.py | 45 +++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index acef0c72c..d129b8ce0 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -107,8 +107,41 @@ def post(self, request): serializer = StudentComplainSerializer(data=data) if serializer.is_valid(): complaint = serializer.save() - # Handle file uploads, notifications, etc. - # Omitted for brevity. + + location = data.get("location", "") + if location == "hall-1": + dsgn = "hall1caretaker" + elif location == "hall-3": + dsgn = "hall3caretaker" + elif location == "hall-4": + dsgn = "hall4caretaker" + elif location == "CC1": + dsgn = "cc1convener" + elif location == "CC2": + dsgn = "CC2 convener" + elif location == "core_lab": + dsgn = "corelabcaretaker" + elif location == "LHTC": + dsgn = "lhtccaretaker" + elif location == "NR2": + dsgn = "nr2caretaker" + elif location == "Maa Saraswati Hostel": + dsgn = "mshcaretaker" + elif location == "Nagarjun Hostel": + dsgn = "nhcaretaker" + elif location == "Panini Hostel": + dsgn = "phcaretaker" + else: + dsgn = "rewacaretaker" + + caretakers = HoldsDesignation.objects.select_related('user', 'working', 'designation').filter(designation__name=dsgn).distinct('user') + + # Send notification to all relevant caretakers + student = 1 + message = "A New Complaint has been lodged" + for caretaker in caretakers: + complaint_system_notif(request.user, caretaker.user, 'lodge_comp_alert', complaint.id, student, message) + return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400) @@ -779,7 +812,13 @@ def post(self, request, comp_id1): complaint.save() # Forward file to service_provider - sup_designations = HoldsDesignation.objects.filter(user=service_provider_details.user_id) + sup_designations = HoldsDesignation.objects.filter(user=service_provider_details.user_id).distinct('user_id') + + #send notification to all the service providers + for sup in sup_designations: + print(sup.user_id) + complaint_system_notif(request.user, User.objects.get(id=sup.user_id), 'comp_assigned_alert', complaint_id, 0, "A new complaint has been assigned to you") + files = File.objects.filter(src_object_id=complaint_id) From e8f9cceb5a59e929b75869e42a641f4361722732 Mon Sep 17 00:00:00 2001 From: jyotiduhan2004 Date: Sun, 23 Mar 2025 21:53:43 +0530 Subject: [PATCH 4/9] generate report page implmented for warden and complaint_admin --- .../applications/complaint_system/admin.py | 4 +- .../applications/complaint_system/models.py | 15 +++ .../applications/complaint_system/views.py | 93 ++++++++++++------- 3 files changed, 78 insertions(+), 34 deletions(-) diff --git a/FusionIIIT/applications/complaint_system/admin.py b/FusionIIIT/applications/complaint_system/admin.py index 631892e13..868b3d59c 100644 --- a/FusionIIIT/applications/complaint_system/admin.py +++ b/FusionIIIT/applications/complaint_system/admin.py @@ -1,9 +1,11 @@ from django.contrib import admin -from .models import Caretaker, StudentComplain, ServiceProvider, Workers, SectionIncharge +from .models import Caretaker, StudentComplain, ServiceProvider, Workers, SectionIncharge, Warden, Complaint_Admin admin.site.register(Caretaker) admin.site.register(Workers) admin.site.register(StudentComplain) admin.site.register(ServiceProvider) admin.site.register(SectionIncharge) +admin.site.register(Warden) +admin.site.register(Complaint_Admin) \ No newline at end of file diff --git a/FusionIIIT/applications/complaint_system/models.py b/FusionIIIT/applications/complaint_system/models.py index 630152bf6..b22256312 100644 --- a/FusionIIIT/applications/complaint_system/models.py +++ b/FusionIIIT/applications/complaint_system/models.py @@ -45,6 +45,15 @@ class Caretaker(models.Model): def __str__(self): return str(self.id) + '-' + str(self.area) + +class Warden(models.Model): + staff_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) + area = models.CharField(choices=Constants.AREA, max_length=20, default='hall-1') + rating = models.IntegerField(default=0) + myfeedback = models.CharField(max_length=400, default="No feedback yet") + + def __str__(self): + return str(self.staff_id) + '-' + str(self.area) class SectionIncharge(models.Model): staff_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) @@ -102,6 +111,12 @@ class Meta: def __str__(self): return str(self.ser_pro_id) + '-' + str(self.type) + +class Complaint_Admin(models.Model): + sup_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE) + + def __str__(self): + return str(self.sup_id) class ServiceAuthority(models.Model): diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index d129b8ce0..83fd682c0 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -8,7 +8,7 @@ from applications.globals.models import User, ExtraInfo, HoldsDesignation from notifications.models import Notification -from .models import Caretaker, StudentComplain, ServiceProvider, ServiceAuthority +from .models import Caretaker,Warden, StudentComplain, ServiceProvider, ServiceAuthority, Complaint_Admin from notification.views import complaint_system_notif from applications.filetracking.sdk.methods import * @@ -23,6 +23,8 @@ StudentComplainSerializer, CaretakerSerializer, ExtraInfoSerializer, + Complaint_AdminSerializer, + WardenSerializer ) # Converted to DRF APIView @@ -39,8 +41,16 @@ def get(self, request): b = ExtraInfo.objects.select_related("user", "department").filter(user=a).first() service_provider_list = ServiceProvider.objects.all() caretaker_list = Caretaker.objects.all() + warden_list=Warden.objects.all() + complaint_admin_list=Complaint_Admin.objects.all() is_service_provider = False is_caretaker = False + is_warden=False + is_complaint_admin = False + for i in complaint_admin_list: + if b.id == i.sup_id_id: + is_complaint_admin = True + break for i in service_provider_list: if b.id == i.ser_pro_id_id: is_service_provider = True @@ -49,10 +59,19 @@ def get(self, request): if b.id == i.staff_id_id: is_caretaker = True break + for i in warden_list: + if b.id == i.staff_id_id: + is_warden = True + break + if is_service_provider: return Response({"user_type": "service_provider", "next_url": "/complaint/service_provider/"}) + elif is_complaint_admin: + return Response({"user_type": "complaint_admin", "next_url": "/complaint/complaint_admin/"}) elif is_caretaker: return Response({"user_type": "caretaker", "next_url": "/complaint/caretaker/"}) + elif is_warden: + return Response({"user_type": "warden", "next_url": "/complaint/warden/"}) elif b.user_type == "student": return Response({"user_type": "student", "next_url": "/complaint/user/"}) elif b.user_type == "staff": @@ -915,46 +934,54 @@ def get(self, request): Generates a report of complaints for the caretaker's area, warden's area, or service_provider's type. """ user = request.user - - is_caretaker = hasattr(user, 'caretaker') - is_service_provider = False - is_warden = hasattr(user, 'warden') + if user.username == 'anil': #hardcoding data for now as complaint_admin role dont exist in database for now + complaints = StudentComplain.objects.all() + else: + is_caretaker = hasattr(user, 'caretaker') + is_service_provider = False + is_complaint_admin = hasattr(user, 'complaint_admin') # Check if the user has the 'complaintadmin' attribute # Check if user is a service_provider - try: - service_provider = ServiceProvider.objects.get(ser_pro_id=user.extrainfo) - is_service_provider = True - except ServiceProvider.DoesNotExist: - is_service_provider = False + try: + service_provider = ServiceProvider.objects.get(ser_pro_id=user.extrainfo) + is_service_provider = True + except ServiceProvider.DoesNotExist: + is_service_provider = False - try: - is_service_authority = ServiceAuthority.objects.get(ser_pro_id=user.extrainfo) - is_service_authority = True - except ServiceAuthority.DoesNotExist: - is_service_authority = False + try: + is_service_authority = ServiceAuthority.objects.get(ser_pro_id=user.extrainfo) + is_service_authority = True + except ServiceAuthority.DoesNotExist: + is_service_authority = False + + try: + warden = Warden.objects.get(staff_id=user.extrainfo) + is_warden = True + except Warden.DoesNotExist: + is_warden = False - if not is_caretaker and not is_service_provider and not is_admin and not is_service_provider and not is_service_provider and not is_service_authority: - return Response({"detail": "Not authorized to generate report."}, status=403) + if not is_caretaker and not is_service_provider and not is_admin and not is_service_provider and not is_service_provider and not is_service_authority and not is_warden: + return Response({"detail": "Not authorized to generate report."}, status=403) - complaints = None + complaints = None # Generate report for service_provider - if is_service_provider: - print(f"Generating report for ServiceProvider {service_provider}") - complaints = StudentComplain.objects.filter(complaint_type=service_provider.type) + if is_service_provider: + print(f"Generating report for ServiceProvider {service_provider}") + complaints = StudentComplain.objects.filter(complaint_type=service_provider.type) # Generate report for caretaker - if is_caretaker and not is_service_provider: - caretaker = get_object_or_404(Caretaker, staff_id=user.extrainfo) - complaints = StudentComplain.objects.filter(location=caretaker.area) - - # if is_warden: - # warden = get_object_or_404(Warden, staff_id=user.extrainfo) - # if complaints: - # complaints = complaints.filter(location=warden.area) - # else: - # complaints = StudentComplain.objects.filter(location=warden.area) - - # Serialize and return the complaints + if is_caretaker and not is_service_provider and not is_warden: + caretaker = get_object_or_404(Caretaker, staff_id=user.extrainfo) + complaints = StudentComplain.objects.filter(location=caretaker.area) + + if is_warden: + warden=get_object_or_404(Warden, staff_id=user.extrainfo) + complaints = StudentComplain.objects.filter(location=warden.area) + + # Generate report for complaint admin + if is_complaint_admin: + complaints = StudentComplain.objects.all() # Complaint admin can see all complaints + serializer = StudentComplainSerializer(complaints, many=True) return Response(serializer.data) From 7616739dc02dcfc3d25bc4d49dfd53bc30a7e701 Mon Sep 17 00:00:00 2001 From: jyotiduhan2004 Date: Sun, 23 Mar 2025 22:23:34 +0530 Subject: [PATCH 5/9] generate report page implmented for warden and complaint_admin --- FusionIIIT/applications/complaint_system/views.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index 83fd682c0..e1b59fbbb 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -934,7 +934,8 @@ def get(self, request): Generates a report of complaints for the caretaker's area, warden's area, or service_provider's type. """ user = request.user - if user.username == 'anil': #hardcoding data for now as complaint_admin role dont exist in database for now + complaint_admin_user = 'anil' + if user.username == complaint_admin_user: #hardcoding data for now as complaint_admin role dont exist in database for now complaints = StudentComplain.objects.all() else: is_caretaker = hasattr(user, 'caretaker') From 2d5fa9b51a02649dc4f7f330c8b3e1a3549e77e6 Mon Sep 17 00:00:00 2001 From: "K.Charan Teja Reddy" <129493881+Charan2437@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:10:55 +0530 Subject: [PATCH 6/9] version 2 of complaint management module with all the latest changes --- .../migrations/0001_initial.py | 11 +------ .../migrations/0002_auto_20250325_1708.py | 32 +++++++++++++++++++ .../applications/complaint_system/models.py | 3 ++ .../complaint_system/serializers.py | 14 +++++++- .../applications/complaint_system/views.py | 2 +- 5 files changed, 50 insertions(+), 12 deletions(-) create mode 100644 FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py diff --git a/FusionIIIT/applications/complaint_system/migrations/0001_initial.py b/FusionIIIT/applications/complaint_system/migrations/0001_initial.py index fea1b5a5a..858747f3e 100644 --- a/FusionIIIT/applications/complaint_system/migrations/0001_initial.py +++ b/FusionIIIT/applications/complaint_system/migrations/0001_initial.py @@ -34,19 +34,10 @@ class Migration(migrations.Migration): ], ), migrations.CreateModel( - name='ServiceProvider', + name='Supervisor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='Electricity', max_length=30)), - ('ser_pro_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), - ], - ), - migrations.CreateModel( - name='ServiceAuthority', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('type', models.CharField(choices=[('Electricity', 'Electricity'), ('carpenter', 'carpenter'), ('plumber', 'plumber'), ('garbage', 'garbage'), ('dustbin', 'dustbin'), ('internet', 'internet'), ('other', 'other')], default='Electricity', max_length=30)), - ('ser_auth_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), ], ), migrations.CreateModel( diff --git a/FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py b/FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py new file mode 100644 index 000000000..5447196d1 --- /dev/null +++ b/FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py @@ -0,0 +1,32 @@ +# Generated by Django 3.1.5 on 2025-03-25 17:08 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('globals', '0002_auto_20241007_2302'), + ('complaint_system', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Complaint_Admin', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('sup_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), + ], + ), + migrations.CreateModel( + name='Warden', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('area', models.CharField(choices=[('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), ('library', 'CC1'), ('computer center', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), ('NR3', 'NR3'), ('Admin building', 'Admin building'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), ('Panini Hostel', 'Panini Hostel')], default='hall-1', max_length=20)), + ('rating', models.IntegerField(default=0)), + ('myfeedback', models.CharField(default='No feedback yet', max_length=400)), + ('staff_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), + ], + ), + ] diff --git a/FusionIIIT/applications/complaint_system/models.py b/FusionIIIT/applications/complaint_system/models.py index b22256312..1bc57d540 100644 --- a/FusionIIIT/applications/complaint_system/models.py +++ b/FusionIIIT/applications/complaint_system/models.py @@ -93,6 +93,9 @@ class StudentComplain(models.Model): upload_complaint = models.FileField(blank=True) comment = models.CharField(max_length=100, default="None") #upload_resolved = models.FileField(blank=True,null=True) + + class meta: + db_table = "complaint_system_student_complain" def __str__(self): return str(self.complainer.user.username) diff --git a/FusionIIIT/applications/complaint_system/serializers.py b/FusionIIIT/applications/complaint_system/serializers.py index d224dcaf3..b083010de 100644 --- a/FusionIIIT/applications/complaint_system/serializers.py +++ b/FusionIIIT/applications/complaint_system/serializers.py @@ -1,5 +1,5 @@ from rest_framework import serializers -from .models import StudentComplain, Caretaker +from .models import StudentComplain, Caretaker, Warden,Complaint_Admin from applications.globals.models import ExtraInfo # Added StudentComplainSerializer @@ -61,6 +61,16 @@ class CaretakerSerializer(serializers.ModelSerializer): class Meta: model = Caretaker fields = '__all__' + +class WardenSerializer(serializers.ModelSerializer): + class Meta: + model = Warden + fields = '__all__' + +class Complaint_AdminSerializer(serializers.ModelSerializer): + class Meta: + model = Complaint_Admin + fields = '__all__' # Serializer for Feedback submission class FeedbackSerializer(serializers.Serializer): @@ -88,3 +98,5 @@ class WorkersSerializer(serializers.ModelSerializer): class Meta: model = Workers fields = '__all__' + + diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index e1b59fbbb..68b724670 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -961,7 +961,7 @@ def get(self, request): except Warden.DoesNotExist: is_warden = False - if not is_caretaker and not is_service_provider and not is_admin and not is_service_provider and not is_service_provider and not is_service_authority and not is_warden: + if not is_caretaker and not is_service_provider and not is_complaint_admin and not is_service_provider and not is_service_provider and not is_service_authority and not is_warden: return Response({"detail": "Not authorized to generate report."}, status=403) complaints = None From e26b6a497149710287a5fd738d0d2518ea0b4fef Mon Sep 17 00:00:00 2001 From: shreySaxena Date: Tue, 15 Apr 2025 16:43:09 +0530 Subject: [PATCH 7/9] Added option to add image by caretaker --- .../applications/complaint_system/models.py | 1 + .../complaint_system/serializers.py | 11 ++-- .../applications/complaint_system/views.py | 54 +++++++++++++++++-- 3 files changed, 60 insertions(+), 6 deletions(-) diff --git a/FusionIIIT/applications/complaint_system/models.py b/FusionIIIT/applications/complaint_system/models.py index 1bc57d540..f859b768d 100644 --- a/FusionIIIT/applications/complaint_system/models.py +++ b/FusionIIIT/applications/complaint_system/models.py @@ -93,6 +93,7 @@ class StudentComplain(models.Model): upload_complaint = models.FileField(blank=True) comment = models.CharField(max_length=100, default="None") #upload_resolved = models.FileField(blank=True,null=True) + upload_resolved = models.FileField(upload_to='resolved_complaints/', blank=True, null=True) class meta: db_table = "complaint_system_student_complain" diff --git a/FusionIIIT/applications/complaint_system/serializers.py b/FusionIIIT/applications/complaint_system/serializers.py index b083010de..434369330 100644 --- a/FusionIIIT/applications/complaint_system/serializers.py +++ b/FusionIIIT/applications/complaint_system/serializers.py @@ -61,12 +61,12 @@ class CaretakerSerializer(serializers.ModelSerializer): class Meta: model = Caretaker fields = '__all__' - + class WardenSerializer(serializers.ModelSerializer): class Meta: model = Warden fields = '__all__' - + class Complaint_AdminSerializer(serializers.ModelSerializer): class Meta: model = Complaint_Admin @@ -78,10 +78,15 @@ class FeedbackSerializer(serializers.Serializer): rating = serializers.IntegerField() # Serializer for Resolve Pending complaints +# class ResolvePendingSerializer(serializers.Serializer): +# yesorno = serializers.ChoiceField(choices=[('Yes', 'Yes'), ('No', 'No')]) +# comment = serializers.CharField(required=False, allow_blank=True) +# serializers.py + class ResolvePendingSerializer(serializers.Serializer): yesorno = serializers.ChoiceField(choices=[('Yes', 'Yes'), ('No', 'No')]) comment = serializers.CharField(required=False, allow_blank=True) -# serializers.py + upload_resolved = serializers.ImageField(required=False, allow_null=True) from rest_framework import serializers from .models import StudentComplain, Caretaker, Workers diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index 68b724670..da9804e4e 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -389,12 +389,43 @@ def get(self, request, feedcomp_id): class ResolvePendingView(APIView): permission_classes = [IsAuthenticated] + # def post(self, request, cid): + # """ + # Allows the caretaker to resolve a pending complaint. + # """ + # serializer = ResolvePendingSerializer(data=request.data) + # print("Incoming data:", request.data) + # if serializer.is_valid(): + # newstatus = serializer.validated_data['yesorno'] + # comment = serializer.validated_data.get('comment', '') + # intstatus = 2 if newstatus == 'Yes' else 3 + # StudentComplain.objects.filter(id=cid).update(status=intstatus, comment=comment) + + # # Send notification to the complainer + # try: + # complainer_details = StudentComplain.objects.select_related('complainer').get(id=cid) + # student = 0 + # if newstatus == 'Yes': + # message = "Congrats! Your complaint has been resolved" + # notification_type = 'comp_resolved_alert' + # else: + # message = "Your complaint has been declined" + # notification_type = 'comp_declined_alert' + + # complaint_system_notif(request.user, complainer_details.complainer.user, notification_type, complainer_details.id, student, message) + # return Response({'success': 'Complaint status updated'}) + # except StudentComplain.DoesNotExist: + # return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + # else: + # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def post(self, request, cid): """ Allows the caretaker to resolve a pending complaint. """ serializer = ResolvePendingSerializer(data=request.data) print("Incoming data:", request.data) + print("Incoming files:", request.FILES) # ✅ Debugging log + if serializer.is_valid(): newstatus = serializer.validated_data['yesorno'] comment = serializer.validated_data.get('comment', '') @@ -402,7 +433,20 @@ def post(self, request, cid): StudentComplain.objects.filter(id=cid).update(status=intstatus, comment=comment) # Send notification to the complainer + # ✅ Get the complaint record try: + complaint = StudentComplain.objects.get(id=cid) + complaint.status = intstatus + complaint.comment = comment + + # ✅ Save the uploaded image if it exists + if 'upload_resolved' in request.FILES: + complaint.upload_resolved = request.FILES['upload_resolved'] + print("✅ Image Saved:", complaint.upload_resolved) + + complaint.save() + + # ✅ Send notification complainer_details = StudentComplain.objects.select_related('complainer').get(id=cid) student = 0 if newstatus == 'Yes': @@ -411,8 +455,10 @@ def post(self, request, cid): else: message = "Your complaint has been declined" notification_type = 'comp_declined_alert' - - complaint_system_notif(request.user, complainer_details.complainer.user, notification_type, complainer_details.id, student, message) + + complaint_system_notif(request.user, complainer_details.complainer.user, notification_type, + complainer_details.id, student, message) + return Response({'success': 'Complaint status updated'}) except StudentComplain.DoesNotExist: return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) @@ -424,12 +470,14 @@ def get(self, request, cid): Returns the details of the complaint to be resolved. """ try: - complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', 'complainer_department').get(id=cid) + complaint = StudentComplain.objects.select_related('complainer', 'complainer_user', + 'complainer_department').get(id=cid) serializer = StudentComplainSerializer(complaint) return Response(serializer.data) except StudentComplain.DoesNotExist: return Response({'error': 'Complaint not found'}, status=status.HTTP_404_NOT_FOUND) + # Converted to DRF APIView class ComplaintDetailView(APIView): permission_classes = [IsAuthenticated] From 52c3f1ca186b09f4731cf9439dbdd9ae5745b719 Mon Sep 17 00:00:00 2001 From: "K.Charan Teja Reddy" <129493881+Charan2437@users.noreply.github.com> Date: Wed, 16 Apr 2025 14:08:32 +0530 Subject: [PATCH 8/9] Made all the final changes and fixed remaining bugs --- .../migrations/0002_auto_20250325_1708.py | 32 ---------------- .../migrations/0003_auto_20250415_1651.py | 19 ++++++++++ .../applications/complaint_system/views.py | 37 ++++++++++--------- 3 files changed, 39 insertions(+), 49 deletions(-) delete mode 100644 FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py create mode 100644 FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py diff --git a/FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py b/FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py deleted file mode 100644 index 5447196d1..000000000 --- a/FusionIIIT/applications/complaint_system/migrations/0002_auto_20250325_1708.py +++ /dev/null @@ -1,32 +0,0 @@ -# Generated by Django 3.1.5 on 2025-03-25 17:08 - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - dependencies = [ - ('globals', '0002_auto_20241007_2302'), - ('complaint_system', '0001_initial'), - ] - - operations = [ - migrations.CreateModel( - name='Complaint_Admin', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('sup_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), - ], - ), - migrations.CreateModel( - name='Warden', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('area', models.CharField(choices=[('hall-1', 'hall-1'), ('hall-3', 'hall-3'), ('hall-4', 'hall-4'), ('library', 'CC1'), ('computer center', 'CC2'), ('core_lab', 'core_lab'), ('LHTC', 'LHTC'), ('NR2', 'NR2'), ('NR3', 'NR3'), ('Admin building', 'Admin building'), ('Rewa_Residency', 'Rewa_Residency'), ('Maa Saraswati Hostel', 'Maa Saraswati Hostel'), ('Nagarjun Hostel', 'Nagarjun Hostel'), ('Panini Hostel', 'Panini Hostel')], default='hall-1', max_length=20)), - ('rating', models.IntegerField(default=0)), - ('myfeedback', models.CharField(default='No feedback yet', max_length=400)), - ('staff_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), - ], - ), - ] diff --git a/FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py b/FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py new file mode 100644 index 000000000..4e2c16cd4 --- /dev/null +++ b/FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py @@ -0,0 +1,19 @@ +# Generated by Django 3.1.5 on 2025-04-15 16:51 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('globals', '0002_auto_20241007_2302'), + ] + + operations = [ + migrations.AddField( + model_name='studentcomplain', + name='upload_resolved', + field=models.FileField(blank=True, null=True, upload_to='resolved_complaints/'), + ), + ] diff --git a/FusionIIIT/applications/complaint_system/views.py b/FusionIIIT/applications/complaint_system/views.py index da9804e4e..d3fcbb390 100644 --- a/FusionIIIT/applications/complaint_system/views.py +++ b/FusionIIIT/applications/complaint_system/views.py @@ -982,50 +982,53 @@ def get(self, request): Generates a report of complaints for the caretaker's area, warden's area, or service_provider's type. """ user = request.user - complaint_admin_user = 'anil' - if user.username == complaint_admin_user: #hardcoding data for now as complaint_admin role dont exist in database for now + try: + complaint_admin_user = Complaint_Admin.objects.get(sup_id=user.extrainfo) complaints = StudentComplain.objects.all() - else: + except Complaint_Admin.DoesNotExist: + complaint_admin_user = None + + if not complaint_admin_user: is_caretaker = hasattr(user, 'caretaker') is_service_provider = False is_complaint_admin = hasattr(user, 'complaint_admin') # Check if the user has the 'complaintadmin' attribute - # Check if user is a service_provider + # Check if user is a service_provider try: - service_provider = ServiceProvider.objects.get(ser_pro_id=user.extrainfo) - is_service_provider = True + service_provider = ServiceProvider.objects.get(ser_pro_id=user.extrainfo) + is_service_provider = True except ServiceProvider.DoesNotExist: - is_service_provider = False + is_service_provider = False try: - is_service_authority = ServiceAuthority.objects.get(ser_pro_id=user.extrainfo) - is_service_authority = True + is_service_authority = ServiceAuthority.objects.get(ser_pro_id=user.extrainfo) + is_service_authority = True except ServiceAuthority.DoesNotExist: - is_service_authority = False + is_service_authority = False try: - warden = Warden.objects.get(staff_id=user.extrainfo) - is_warden = True + warden = Warden.objects.get(staff_id=user.extrainfo) + is_warden = True except Warden.DoesNotExist: - is_warden = False + is_warden = False if not is_caretaker and not is_service_provider and not is_complaint_admin and not is_service_provider and not is_service_provider and not is_service_authority and not is_warden: return Response({"detail": "Not authorized to generate report."}, status=403) complaints = None - # Generate report for service_provider + # Generate report for service_provider if is_service_provider: print(f"Generating report for ServiceProvider {service_provider}") - complaints = StudentComplain.objects.filter(complaint_type=service_provider.type) + complaints = StudentComplain.objects.filter(complaint_type=service_provider.type, status__in=[1, 2, 3]) # Include resolved complaints - # Generate report for caretaker + # Generate report for caretaker if is_caretaker and not is_service_provider and not is_warden: caretaker = get_object_or_404(Caretaker, staff_id=user.extrainfo) complaints = StudentComplain.objects.filter(location=caretaker.area) if is_warden: - warden=get_object_or_404(Warden, staff_id=user.extrainfo) + warden = get_object_or_404(Warden, staff_id=user.extrainfo) complaints = StudentComplain.objects.filter(location=warden.area) # Generate report for complaint admin From c6af171ec4795204cf6868bc474c6dc00e4ad51d Mon Sep 17 00:00:00 2001 From: "K.Charan Teja Reddy" <129493881+Charan2437@users.noreply.github.com> Date: Wed, 16 Apr 2025 14:09:33 +0530 Subject: [PATCH 9/9] Made all the final changes and fixed remaining bugs --- .../migrations/0003_auto_20250415_1651.py | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py diff --git a/FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py b/FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py deleted file mode 100644 index 4e2c16cd4..000000000 --- a/FusionIIIT/applications/complaint_system/migrations/0003_auto_20250415_1651.py +++ /dev/null @@ -1,19 +0,0 @@ -# Generated by Django 3.1.5 on 2025-04-15 16:51 - -from django.db import migrations, models -import django.db.models.deletion - - -class Migration(migrations.Migration): - - dependencies = [ - ('globals', '0002_auto_20241007_2302'), - ] - - operations = [ - migrations.AddField( - model_name='studentcomplain', - name='upload_resolved', - field=models.FileField(blank=True, null=True, upload_to='resolved_complaints/'), - ), - ]