diff --git a/FusionIIIT/applications/health_center/api/serializers.py b/FusionIIIT/applications/health_center/api/serializers.py index edfaa6dc7..761e039e0 100644 --- a/FusionIIIT/applications/health_center/api/serializers.py +++ b/FusionIIIT/applications/health_center/api/serializers.py @@ -1,20 +1,20 @@ -# from django.contrib.auth import get_user_model -# from rest_framework.authtoken.models import Token -# from rest_framework import serializers -# from applications.health_center.models import * +from django.contrib.auth import get_user_model +from rest_framework.authtoken.models import Token +from rest_framework import serializers +from applications.health_center.models import * -# class DoctorSerializer(serializers.ModelSerializer): +class DoctorSerializer(serializers.ModelSerializer): -# class Meta: -# model=Doctor -# fields=('__all__') + class Meta: + model=Doctor + fields=('__all__') -# class PathologistSerializer(serializers.ModelSerializer): +class PathologistSerializer(serializers.ModelSerializer): -# class Meta: -# model=Pathologist -# fields=('__all__') + class Meta: + model=Pathologist + fields=('__all__') # class ComplaintSerializer(serializers.ModelSerializer): @@ -47,25 +47,45 @@ # model=Expiry # fields=('__all__') -# class DoctorsScheduleSerializer(serializers.ModelSerializer): +class DoctorsScheduleSerializer(serializers.ModelSerializer): -# class Meta: -# model=Doctors_Schedule -# fields=('__all__') -# class PathologistScheduleSerializer(serializers.ModelSerializer): + class Meta: + model=Doctors_Schedule + fields=('__all__') +class PathologistScheduleSerializer(serializers.ModelSerializer): -# class Meta: -# model=Pathologist_Schedule -# fields=('__all__') - + class Meta: + model=Pathologist_Schedule + fields=('__all__') +class PrescriptionSerializer(serializers.ModelSerializer): + + class Meta: + model=All_Prescription + fields=('__all__') +class followupSerializer(serializers.ModelSerializer): + + class Meta: + model=Prescription_followup + fields=('__all__') -# class AnnouncementSerializer(serializers.ModelSerializer): +class prescmedSerializer(serializers.ModelSerializer): -# class Meta: -# model=Announcements -# fields=('__all__') + class Meta: + model=All_Prescribed_medicine + fields=('__all__') +class ComplaintSerializer(serializers.ModelSerializer): + + class Meta: + model=Complaint + fields=('__all__') + +class AnnouncementSerializer(serializers.ModelSerializer): + + class Meta: + model=Announcements + fields=['message'] # class CounterSerializer(serializers.ModelSerializer): @@ -107,8 +127,8 @@ # model=Hospital_admit # fields=('__all__') -# class MedicalReliefSerializer(serializers.ModelSerializer): +class MedicalReliefSerializer(serializers.ModelSerializer): -# class Meta: -# model=medical_relief -# fields=('__all__') \ No newline at end of file + class Meta: + model=medical_relief + fields=('__all__') \ No newline at end of file diff --git a/FusionIIIT/applications/health_center/api/urls.py b/FusionIIIT/applications/health_center/api/urls.py index 30e998166..d80a76023 100644 --- a/FusionIIIT/applications/health_center/api/urls.py +++ b/FusionIIIT/applications/health_center/api/urls.py @@ -3,7 +3,10 @@ from . import views urlpatterns = [ - + # url(r'^trial/$', views.trial,), + # url(r'^test/$',views.vamshi,), + url(r'^compounder/$',views.compounder_api_handler,), + url(r'^student/$',views.student_api_handler,), # url(r'^compounder/$', views.compounder_view_api, name='compounder_view_api'), # url(r'^compounder/request$', views.compounder_request_api , name='compounder_request_api'), # url(r'^student/$', views.student_view_api, name='student_view'), diff --git a/FusionIIIT/applications/health_center/api/views.py b/FusionIIIT/applications/health_center/api/views.py index d900c1461..376da38c3 100644 --- a/FusionIIIT/applications/health_center/api/views.py +++ b/FusionIIIT/applications/health_center/api/views.py @@ -1,23 +1,1484 @@ -# from django.contrib.auth import get_user_model -# from django.shortcuts import get_object_or_404, redirect -# from applications.globals.models import ExtraInfo, HoldsDesignation, Designation, DepartmentInfo -# from applications.health_center.models import * -# from datetime import datetime, timedelta, time,date -# from django.db import transaction -# from notification.views import healthcare_center_notif -# from rest_framework.permissions import IsAuthenticated -# from rest_framework.authentication import TokenAuthentication -# from rest_framework import status -# from rest_framework.decorators import api_view, permission_classes,authentication_classes -# from rest_framework.permissions import AllowAny -# from rest_framework.response import Response - - -# from . import serializers - -# from notifications.models import Notification - -# User = get_user_model() +from django.contrib.auth import get_user_model +from django.shortcuts import get_object_or_404, redirect +from applications.globals.models import ExtraInfo, HoldsDesignation, Designation, DepartmentInfo +from django.db import transaction +from notification.views import healthcare_center_notif +from rest_framework.permissions import IsAuthenticated +from rest_framework.authentication import TokenAuthentication +from rest_framework import status +from rest_framework.decorators import api_view, permission_classes,authentication_classes +from rest_framework.permissions import AllowAny +from rest_framework.response import Response +from django.views.decorators.csrf import csrf_protect +from django.views.decorators.csrf import csrf_exempt +import pandas as pd +from django.db import transaction +from datetime import datetime, timedelta,date +from django.core import serializers +from applications.filetracking.models import File +from django.http import HttpResponse, JsonResponse +from notification.views import healthcare_center_notif +from applications.health_center.models import ( Doctor, Stock_entry,Present_Stock,All_Medicine, + Doctors_Schedule,Pathologist_Schedule, + Pathologist, medical_relief, MedicalProfile,All_Prescription,All_Prescribed_medicine, + Prescription_followup,files,Required_medicine,Announcements,Complaint) +from applications.filetracking.sdk.methods import * +from django.core.exceptions import ObjectDoesNotExist +from django.shortcuts import get_object_or_404 +from django.db.models import Q +from applications.globals.models import ExtraInfo +from applications.hr2.models import EmpDependents +import json +from . import serializers +import base64 + +from notifications.models import Notification + +User = get_user_model() + +def convert_to_am_pm(time_str): + """Converts time in HH:MM:SS format to AM/PM format.""" + + time_obj = datetime.strptime(time_str, "%H:%M:%S") + return time_obj.strftime("%I:%M %p") + +@api_view(['POST']) +def compounder_api_handler(request): + request_body = request.body.decode('utf-8') + request_body = json.loads(request_body) + ''' + handles rendering of pages for compounder view + ''' + # compounder response to patients feedback + if 'feed_com' in request.POST: + pk = request.POST.get('com_id') + feedback = request.POST.get('feed') + comp_id = ExtraInfo.objects.select_related('user','department').filter(user_type='compounder') + Complaint.objects.select_related('user_id','user_id__user','user_id__department').filter(id=pk).update(feedback=feedback) + data = {'feedback': feedback} + for cmp in comp_id: + healthcare_center_notif(request.user, cmp.user, 'feedback_res','') + return JsonResponse(data) + + # updating new doctor info in db + elif 'add_doctor' in request_body: + doctor=request_body['new_doctor'] + specialization=request_body['specialization'] + phone=request_body['phone'] + Doctor.objects.create( + doctor_name=doctor, + doctor_phone=phone, + specialization=specialization, + active=True + ) + data={'status':1, 'doctor':doctor, 'specialization':specialization, 'phone':phone} + return JsonResponse(data) + + # updating new pathologist info in db + elif 'add_pathologist' in request_body: + doctor=request_body['new_pathologist'] + specialization=request_body['specialization'] + phone=request_body['phone'] + Pathologist.objects.create( + pathologist_name=doctor, + pathologist_phone=phone, + specialization=specialization, + active=True + ) + data={'status':1, 'pathologist_name':doctor, 'specialization':specialization, 'pathologist_phone':phone} + return JsonResponse(data) + + + + # remove doctor by changing active status + elif 'remove_doctor' in request_body: + doctor=request_body['doctor_active'] + Doctor.objects.filter(id=doctor).update(active=False) + doc=Doctor.objects.get(id=doctor).doctor_name + data={'status':1, 'id':doctor, 'doc':doc} + return JsonResponse(data) + + # remove pathologist by changing active status + elif 'remove_pathologist' in request_body: + doctor=request_body['pathologist_active'] + Pathologist.objects.filter(id=doctor).update(active=False) + doc=Pathologist.objects.get(id=doctor).pathologist_name + data={'status':1, 'id':doctor, 'doc':doc} + return JsonResponse(data) + + elif "get_annoucements" in request_body: + announcements_data=Announcements.objects.all().order_by('-id').values() + serializer = serializers.AnnouncementSerializer(announcements_data,many=True) + return JsonResponse({'status':1, 'announcements' : serializer.data}) + + elif "get_feedback" in request_body: + all_complaints = Complaint.objects.select_related('user_id','user_id__user','user_id__department').all().order_by('-id') + serializer = serializers.ComplaintSerializer(all_complaints,many=True) + return JsonResponse({'status':1,"complaints":serializer.data}) + + elif "get_relief" in request_body: + inbox_files=view_inbox(username=request.user.username,designation='Compounder',src_module='health_center') + medicalrelief=medical_relief.objects.all() + + inbox=[] + for ib in inbox_files: + dic={} + for mr in medicalrelief: + if mr.file_id==int(ib['id']): + dic['id']=ib['id'] + dic['uploader']=ib['uploader'] + dic['upload_date']=datetime.fromisoformat(ib['upload_date']).date() + dic['desc']=mr.description + # dic['file']=view_file(file_id=ib['id'])['upload_file'] + dic['status']=mr.compounder_forward_flag + dic['status1']=mr.acc_admin_forward_flag + dic['status2']=mr.compounder_reject_flag + inbox.append(dic) + + return JsonResponse({'status':1, 'relief': inbox}) + + elif 'get_application' in request_body: + inbox_files=view_inbox(username=request.user.username,designation='Compounder',src_module='health_center') + medicalrelief=medical_relief.objects.all() + relief_id = request_body['aid'] + inbox=[] + for ib in inbox_files: + if int(ib['id']) == int(relief_id) : + dic={} + for mr in medicalrelief: + if mr.file_id==int(ib['id']): + dic['id']=ib['id'] + dic['uploader']=ib['uploader'] + dic['upload_date']=datetime.fromisoformat(ib['upload_date']).date() + dic['desc']=mr.description + # dic['file']=view_file(file_id=ib['id'])['upload_file'] + status = "Pending" + if mr.acc_admin_forward_flag : + status = "Approved" + elif mr.compounder_forward_flag : + status = "Forwarded" + elif mr.compounder_reject_flag : + status = "Rejected" + dic['status']=status + inbox.append(dic) + return JsonResponse({'status':1,'inbox':inbox[0]}) + + elif 'get_doctors' in request_body : + doctors = Doctor.objects.filter(active=True).order_by('id') + serializer = serializers.DoctorSerializer(doctors,many=True) + return JsonResponse({ 'status':1 , 'doctors':serializer.data }) + + elif 'get_pathologists' in request_body : + pathologists = Pathologist.objects.filter(active=True).order_by('id') + serializer = serializers.PathologistSerializer(pathologists,many=True) + return JsonResponse({'status':1,'pathologists':serializer.data}) + + elif 'get_doctor_schedule' in request_body : + # schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('day','doctor_id') + doctors=Doctor.objects.filter(active=True).order_by('id') + schedules = [] + for doctor in doctors : + obj1 = {} + schedule = Doctors_Schedule.objects.filter(doctor_id = doctor.id) + availability = [] + for sch in schedule : + obj = {} + obj['day'] = sch.day + obj['time'] = str(convert_to_am_pm(str(sch.from_time))) + "-" +str(convert_to_am_pm(str(sch.to_time))) + availability.append(obj) + obj1['name'] = doctor.doctor_name + obj1['specialization'] = doctor.specialization + obj1['availability'] = availability + schedules.append(obj1) + + return JsonResponse({ 'status':1, 'schedule':schedules }) + + elif 'get_pathologist_schedule' in request_body : + # schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('day','doctor_id') + pathologists=Pathologist.objects.filter(active=True).order_by('id') + schedules = [] + for pathologist in pathologists : + obj1 = {} + schedule = Pathologist_Schedule.objects.filter(pathologist_id = pathologist.id) + availability = [] + for sch in schedule : + obj = {} + obj['day'] = sch.day + obj['time'] = str(convert_to_am_pm(str(sch.from_time))) + "-" +str(convert_to_am_pm(str(sch.to_time))) + availability.append(obj) + obj1['name'] = pathologist.pathologist_name + obj1['specialization'] = pathologist.specialization + obj1['availability'] = availability + schedules.append(obj1) + + return JsonResponse({ 'status':1, 'schedule':schedules }) + + + + elif 'add_stock' in request_body: + try: + id = request_body['medicine_id'] + medicine_id = All_Medicine.objects.get(id = id) + qty = int(request_body['quantity']) + supplier=request_body['supplier'] + expiry=request_body['expiry_date'] + tot_rows = Stock_entry.objects.all().count() + tot_rows1 = Present_Stock.objects.all().count() + stk=Stock_entry.objects.create( + id = tot_rows+1, + quantity=qty, + medicine_id=medicine_id, + supplier=supplier, + Expiry_date=expiry, + date=date.today() + ) + Present_Stock.objects.create( + id = tot_rows1+1, + quantity=qty, + stock_id=stk, + medicine_id=medicine_id, + Expiry_date=expiry + ) + if Required_medicine.objects.filter(medicine_id = medicine_id).exists(): + req=Required_medicine.objects.get(medicine_id = medicine_id) + req.quantity+=qty + if(req.quantity Req.threshold : + Req.delete() + else : Req.save() + else : + medicine_stock = Present_Stock.objects.filter(Q(medicine_id = threshold_med) & Q(Expiry_date__gt = date.today())) + qty=0 + for med in medicine_stock: + qty+=med.quantity + if qty < threshold_med.threshold : + Required_medicine.objects.create( + medicine_id = threshold_med, + quantity = qty, + threshold = threshold_med.threshold + ) + status=1 + except: + status=0 + finally: + data={'status':status} + return JsonResponse(data) + # edit schedule for doctors + elif 'edit_1' in request_body: + doctor = request_body['doctor'] + day = request_body['day'] + time_in = request_body['time_in'] + time_out = request_body['time_out'] + room = request_body['room'] + schedule = Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor, day=day) + doctor_id = Doctor.objects.get(id=doctor) + if schedule.count() == 0: + Doctors_Schedule.objects.create(doctor_id=doctor_id, day=day, room=room, + from_time=time_in, to_time=time_out) + else: + Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(room=room) + Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(from_time=time_in) + Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=day).update(to_time=time_out) + data={'status':1} + return JsonResponse(data) + + + # remove schedule for a doctor + elif 'rmv' in request_body: + doctor = request_body['doctor'] + day = request_body['day'] + Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor, day=day).delete() + data = {'status': 1} + return JsonResponse(data) + + + # edit schedule for pathologists + elif 'edit12' in request_body: + doctor = request_body['pathologist'] + day = request_body['day'] + time_in = request_body['time_in'] + time_out = request_body['time_out'] + room = request_body['room'] + pathologist_id = Pathologist.objects.get(id=doctor) + schedule = Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=doctor, day=day) + if schedule.count() == 0: + Pathologist_Schedule.objects.create(pathologist_id=pathologist_id, day=day, room=room, + from_time=time_in, to_time=time_out) + else: + Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=pathologist_id, day=day).update(room=room) + Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=pathologist_id, day=day).update(from_time=time_in) + Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=pathologist_id, day=day).update(to_time=time_out) + data={'status':1} + return JsonResponse(data) + + + # remove schedule for a doctor + elif 'rmv1' in request_body: + doctor = request_body['pathologist'] + day = request_body['day'] + Pathologist_Schedule.objects.select_related('pathologist_id').filter(pathologist_id=doctor, day=day).delete() + data = {'status': 1} + return JsonResponse(data) + + + elif 'add_medicine' in request_body: + medicine = request_body['new_medicine'] + # quantity = request.POST.get('new_quantity') + threshold = request_body['threshold'] + brand_name = request_body['brand_name'] + constituents = request_body['constituents'] + manufacture_name = request_body['manufacture_name'] + packsize = request_body['packsize'] + # new_supplier = request.POST.get('new_supplier') + # new_expiry_date = request.POST.get('new_expiry_date') + tot_rows = All_Medicine.objects.all().count() + All_Medicine.objects.create( + id = tot_rows+1, + medicine_name=medicine, + brand_name=brand_name, + constituents=constituents, + threshold=threshold, + manufacturer_name=manufacture_name, + pack_size_label=packsize + ) + # Stock.objects.create( + # medicine_name=medicine, + # quantity=quantity, + # threshold=threshold + # ) + # medicine_id = Stock.objects.get(medicine_name=medicine) + # Expiry.objects.create( + # medicine_id=medicine_id, + # quantity=quantity, + # supplier=new_supplier, + # expiry_date=new_expiry_date, + # returned=False, + # return_date=None, + # date=datetime.now() + # ) + data = {'medicine': medicine, 'threshold': threshold,} + return JsonResponse(data) + + elif 'get_prescription' in request_body: + prescription_id = request_body['presc_id'] + prescription = All_Prescription.objects.get(id=prescription_id) + pre_medicine = All_Prescribed_medicine.objects.filter(prescription_id=prescription) + doctors=Doctor.objects.filter(active=True).order_by('id') + follow_presc =Prescription_followup.objects.filter(prescription_id=prescription).order_by('-id') + prescriptions=[] + for f_presc in follow_presc: + obj={} + obj['id'] = f_presc.id + obj['doctor'] = f_presc.Doctor_id.doctor_name + obj['diseaseDetails'] = f_presc.details + obj['followUpDate'] = f_presc.date + revoked=[] + for med in pre_medicine : + if med.revoked == True and med.revoked_prescription.id == f_presc.id : + obj1={} + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + revoked.append(obj1) + obj['revoked_medicines'] = revoked + presc_med = [] + for med in pre_medicine : + if med.prescription_followup_id == f_presc : + obj1={} + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + presc_med.append(obj1) + obj['medicines'] = presc_med + tests = "No Test suggested" + if f_presc.test!="" : + tests = f_presc.test + obj['tests'] = tests + obj['file_id'] = f_presc.file_id + prescriptions.append(obj) + obj={} + obj['id'] = 0 + obj['doctor'] = prescription.doctor_id.doctor_name + obj['diseaseDetails'] = prescription.details + obj['followUpDate'] = prescription.date + revoked=[] + obj['revoked_medicines'] = revoked + presc_med = [] + for med in pre_medicine : + if med.prescription_followup_id == None : + obj1={} + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + presc_med.append(obj1) + obj['medicines'] = presc_med + tests = "No Test suggested" + if prescription.test!="" : + tests = prescription.test + obj['tests'] = tests + obj['file_id'] = prescription.file_id + prescriptions.append(obj) + presc_serializer = serializers.PrescriptionSerializer(prescription) + + not_revoked=[] + for med in pre_medicine: + if med.revoked==False: + obj1={} + obj1['id'] = med.id + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + not_revoked.append(obj1) + return JsonResponse({'status':1, 'prescription':presc_serializer.data, 'prescriptions':prescriptions , 'not_revoked' : not_revoked}) + + + + elif 'get_stock' in request_body: + try: + medicine_name_and_id = request_body['medicine_name_for_stock'] + medicine_name = medicine_name_and_id.split(",")[0] + id=0 + if(len(medicine_name_and_id.split(",")) > 1) : + id=medicine_name_and_id.split(",")[1] + if id == 0: + status=1 + similar_name_qs = All_Medicine.objects.filter(brand_name__istartswith=medicine_name)[:10] + else : + status=2 + similar_name_qs = All_Medicine.objects.filter(id=id) + similar_name = list(similar_name_qs.values('id', 'medicine_name','constituents','manufacturer_name','pack_size_label','brand_name','threshold')) + val_to_return = [] + + try: + med = All_Medicine.objects.get(id = id) + stk = Stock_entry.objects.filter(medicine_id=med).order_by('Expiry_date') + for s in stk: + if s.Expiry_date > date.today(): + obj = {} + obj['brand_name'] = s.medicine_id.brand_name + obj['supplier'] = s.supplier + obj['expiry'] = s.Expiry_date + p_s = Present_Stock.objects.get(stock_id=s) + if p_s.quantity > 0: + obj['quantity'] = p_s.quantity + obj['id'] = p_s.id + val_to_return.append(obj) + except All_Medicine.DoesNotExist: + val_to_return = [] + except Present_Stock.DoesNotExist: + val_to_return = [] + except Exception as e: + val_to_return = [] + finally: + return JsonResponse({"val": val_to_return, "sim": similar_name, "status": status}) + elif 'medicine_name_b' in request.POST: + user_id = request.POST.get('user') + if not User.objects.filter(username__iexact = user_id).exists(): + return JsonResponse({"status":-2}) + quantity = int(request.POST.get('quantity')) + days = int(request.POST.get('days')) + times = int(request.POST.get('times')) + medicine_id = request.POST.get('medicine_name_b') + stock = request.POST.get('stock') + medicine_brand_name = medicine_id.split(",")[0] + id= medicine_id.split(",")[1] + med_name = All_Medicine.objects.get(id=id).brand_name + if(stock == "" or stock == "N/A at moment") : + return JsonResponse({"status":1,"med_name":med_name,"id":id}) + stk=stock.split(",") + qty = int(stk[2]) + status=1 + if quantity>qty : status=0 + return JsonResponse({"status":status,"med_name":med_name,"id":id}) + + + elif 'user_for_dependents' in request_body: + user = request_body['user_for_dependents'] + if not User.objects.filter(username__iexact = user).exists(): + return JsonResponse({"status":-1}) + user_id = User.objects.get(username__iexact = user) + info = ExtraInfo.objects.get(user = user_id) + dep_info = EmpDependents.objects.filter(extra_info = info) + dep=[] + for d in dep_info: + obj={} + obj['name'] = d.name + obj['relation'] = d.relationship + dep.append(obj) + if(len(dep) == 0) : + return JsonResponse({'status':-2}) + return JsonResponse({'status':1,'dep':dep}) + elif 'prescribe_b' in request_body: + user_id = request_body['user'] + doctor_id = request_body['doctor'] + if not User.objects.filter(username__iexact = user_id).exists(): + return JsonResponse({"status":-1}) + if doctor_id == 'null' : + doctor = None + else: + doctor = Doctor.objects.get(doctor_name=doctor_id) + + + is_dependent=request_body['is_dependent'] + fid=0 + uploaded_file = request_body['file'] + print(uploaded_file) + if uploaded_file != None : + file_binary = base64.b64decode(uploaded_file) + new_file=files.objects.create( + file_data=file_binary + ) + fid=new_file.id + if is_dependent == "self": + pres=All_Prescription.objects.create( + user_id = user_id, + doctor_id=doctor, + details = request_body['details'], + date=date.today(), + test=request_body['tests'], + file_id=fid + ) + else : + pres=All_Prescription.objects.create( + user_id = user_id, + doctor_id=doctor, + details = request_body['details'], + date=date.today(), + test=request_body['tests'], + is_dependent = True, + dependent_name = request_body['dependent_name'], + dependent_relation = request_body['dependent_relation'], + file_id=fid + ) + # designation=request.POST.get('user') + # d = HoldsDesignation.objects.get(user__username=designation) + # send_file_id = create_file( + # uploader=request.user.username, + # uploader_designation=request.session['currentDesignationSelected'], + # receiver=designation, + # receiver_designation=d.designation, + # src_module="health_center", + # src_object_id=str(pres.id), + # file_extra_JSON={"value": 2}, + # attached_file=uploaded_file + # ) + # pres.file_id=send_file_id + # pres.save() + + medicine = request_body['pre_medicine'] + + for med in medicine: + med_name = med["brand_name"] + id=med_name.split(",")[1] + quant = int(med['quantity']) + days = med['Days'] + times = med['Times'] + stock = med['astock'] + med_id = All_Medicine.objects.get(id=id) + if(stock == "," or stock == 'N/A at moment') : + All_Prescribed_medicine.objects.create( + prescription_id = pres, + medicine_id = med_id, + quantity = quant, + days = days, + times=times + ) + else : + stk = stock.split(",") + p_stock = Present_Stock.objects.get(id=int(stk[1])) + All_Prescribed_medicine.objects.create( + prescription_id = pres, + medicine_id = med_id, + stock = p_stock, + quantity = quant, + days = days, + times=times + ) + p_stock.quantity -= quant + p_stock.save() + stock_of_medicine = Present_Stock.objects.filter(Q(medicine_id = med_id) & Q( Expiry_date__gt = date.today())) + qty=0 + for stk in stock_of_medicine : + qty+=stk.quantity + + if qtyquantity: + # for e in expiry: + # q=e.quantity + # em=e.id + # if q>quantity: + # q=q-quantity + # Expiry.objects.select_related('medicine_id').filter(id=em).update(quantity=q) + # qty = Stock.objects.get(medicine_name=medicine_id).quantity + # qty = qty-quantity + # Stock.objects.filter(medicine_name=medicine_id).update(quantity=qty) + # break + # else: + # quan=Expiry.objects.select_related('medicine_id').get(id=em).quantity + # Expiry.objects.select_related('medicine_id').filter(id=em).update(quantity=0) + # qty = Stock.objects.get(medicine_name=medicine_id).quantity + # qty = qty-quan + # Stock.objects.filter(medicine_name=medicine_id).update(quantity=qty) + # quantity=quantity-quan + # status = 1 + + # else: + # status = 0 + # Medicine.objects.select_related('patient','patient__user','patient__department').all().delete() + + + # healthcare_center_notif(request.user, user.user, 'presc','') + # data = {'status': status} + # return JsonResponse(data) + return JsonResponse({"status":1}) + + elif 'presc_followup' in request_body: + pre_id=request_body["pre_id"] + presc = All_Prescription.objects.get(id=int(pre_id)) + + doctor_id = request_body['doctor'] + if doctor_id == 'null' : + doctor = None + else: + doctor = Doctor.objects.get(doctor_name=doctor_id) + + fid=0 + uploaded_file = request_body['file'] + print(uploaded_file) + if uploaded_file != None : + file_binary = base64.b64decode(uploaded_file) + new_file=files.objects.create( + file_data=file_binary + ) + fid=new_file.id + + followup = Prescription_followup.objects.create( + prescription_id=presc, + Doctor_id=doctor, + details = request_body['details'], + test = request_body['tests'], + date = date.today(), + file_id = fid + ) + medicine= request_body['pre_medicine'] + for med in medicine: + med_name = med["brand_name"] + id = med_name.split(',')[1] + quant = int(med['quantity']) + days = med['Days'] + times = med['Times'] + stock = med['astock'] + med_id = All_Medicine.objects.get(id = id) + + if(stock == ',' or stock == "N/A at moment,"): + All_Prescribed_medicine.objects.create( + prescription_id = presc, + medicine_id = med_id, + quantity = quant, + days = days, + times=times, + prescription_followup_id = followup + ) + else : + stk = stock.split(",") + p_stock = Present_Stock.objects.get(id=int(stk[1])) + All_Prescribed_medicine.objects.create( + prescription_id = presc, + medicine_id = med_id, + stock = p_stock, + quantity = quant, + days = days, + times=times, + prescription_followup_id = followup + ) + p_stock.quantity -= quant + p_stock.save() + stock_of_medicine = Present_Stock.objects.filter(Q(medicine_id = med_id) & Q(Expiry_date__gt = date.today())) + qty=0 + for stk in stock_of_medicine : + qty+=stk.quantity + + if qty 1, + 'has_next': new_current_page < total_pages, + 'previous_page_number': new_current_page - 1 if new_current_page > 1 else None, + 'next_page_number': new_current_page + 1 if new_current_page < total_pages else None, + }) + elif 'datatype' in request_body and request_body['datatype'] == 'manage_stock_view': + search = request_body['search_view_stock'] + page_size_stock = 2 + new_current_page_stock = int(request_body['page_stock_view']) + new_offset_stock = (new_current_page_stock - 1) * page_size_stock + new_live_meds = [] + new_live =Stock_entry.objects.filter(Q(Expiry_date__gte=date.today()) & Q( Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).order_by('Expiry_date')[new_offset_stock:new_offset_stock + page_size_stock] + total_pages_stock = ( Stock_entry.objects.filter(Q(Expiry_date__gte=date.today()) & Q( Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).count() + page_size_stock - 1) // page_size_stock + for e in new_live: + obj={} + obj['id']=e.id + obj['medicine_id']=e.medicine_id.brand_name + obj['Expiry_date']=e.Expiry_date + obj['supplier']=e.supplier + try: + qty=Present_Stock.objects.get(stock_id=e).quantity + except: + qty=0 + obj['quantity']=qty + new_live_meds.append(obj) + return JsonResponse({ + 'report_stock_view': new_live_meds, + 'page_stock_view': new_current_page_stock, + 'total_pages_stock_view': total_pages_stock, + 'has_previous': new_current_page_stock > 1, + 'has_next': new_current_page_stock < total_pages_stock, + 'previous_page_number': new_current_page_stock - 1 if new_current_page_stock > 1 else None, + 'next_page_number': new_current_page_stock + 1 if new_current_page_stock < total_pages_stock else None, + }) + elif 'datatype' in request_body and request_body['datatype'] == 'manage_stock_expired': + search = request_body['search_view_expired'] + new_page_size_stock_expired = 2 + new_current_page_stock_expired = int(request_body['page_stock_expired']) + new_offset_stock_expired = (new_current_page_stock_expired - 1 )* new_page_size_stock_expired + new_expired=[] + new_expiredData=Stock_entry.objects.filter(Q(Expiry_date__lt=date.today())&Q( Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).order_by('Expiry_date')[new_offset_stock_expired:new_offset_stock_expired + new_page_size_stock_expired] + new_total_pages_stock_expired = ( Stock_entry.objects.filter(Q(Expiry_date__lt=date.today())&Q( Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).count() + new_page_size_stock_expired - 1) // new_page_size_stock_expired + for e in new_expiredData: + obj={} + obj['medicine_id']=e.medicine_id.brand_name + obj['Expiry_date']=e.Expiry_date + obj['supplier']=e.supplier + try: + qty=Present_Stock.objects.get(stock_id=e).quantity + except: + qty=0 + obj['quantity']=qty + new_expired.append(obj) + return JsonResponse({ + 'report_stock_expired': new_expired, + 'page_stock_expired': new_current_page_stock_expired, + 'total_pages_stock_view': new_total_pages_stock_expired, + 'has_previous': new_current_page_stock_expired > 1, + 'has_next': new_current_page_stock_expired < new_total_pages_stock_expired, + 'previous_page_number': new_current_page_stock_expired - 1 if new_current_page_stock_expired > 1 else None, + 'next_page_number': new_current_page_stock_expired + 1 if new_current_page_stock_expired < new_total_pages_stock_expired else None, + }) + elif 'datatype' in request_body and request_body['datatype'] == 'manage_stock_required': + search = request_body['search_view_required'] + new_page_size_stock_required = 2 + new_current_page_stock_required = int(request_body['page_stock_required']) + new_offset_stock_required = (new_current_page_stock_required - 1 )* new_page_size_stock_required + new_required=[] + new_requiredData=Required_medicine.objects.filter( Q(medicine_id__brand_name__icontains = search))[new_offset_stock_required:new_offset_stock_required + new_page_size_stock_required] + new_total_pages_stock_required = (Required_medicine.objects.filter( Q(medicine_id__brand_name__icontains = search)).count() + new_page_size_stock_required - 1) // new_page_size_stock_required + for e in new_requiredData: + obj={} + obj['medicine_id']=e.medicine_id.brand_name + obj['quantity']=e.quantity + obj['threshold']=e.threshold + new_required.append(obj) + return JsonResponse({ + 'report_stock_required': new_required, + 'page_stock_required': new_current_page_stock_required, + 'total_pages_stock_required': new_total_pages_stock_required, + 'has_previous': new_current_page_stock_required > 1, + 'has_next': new_current_page_stock_required < new_total_pages_stock_required, + 'previous_page_number': new_current_page_stock_required - 1 if new_current_page_stock_required > 1 else None, + 'next_page_number': new_current_page_stock_required + 1 if new_current_page_stock_required < new_total_pages_stock_required else None, + }) + + elif 'search_patientlog' in request.POST: + search = request.POST.get('search_patientlog') + current_page = 1 + page_size_prescription = 2 # Default to 2 if not specified + offset = (current_page - 1) * page_size_prescription + prescriptions = All_Prescription.objects.filter(Q(user_id__icontains = search) | Q(details__icontains = search)).order_by('-date', '-id')[offset:offset + page_size_prescription] + + report = [] + for pre in prescriptions: + doc = None + if pre.doctor_id != None : doc=pre.doctor_id.doctor_name + dic = { + 'id': pre.pk, + 'user_id': pre.user_id, + 'doctor_id': doc, + 'date': pre.date, + 'details': pre.details, + 'test': pre.test, + 'file_id': pre.file_id, + # 'file': view_file(file_id=pre.file_id)['upload_file'] if pre.file_id else None + } + report.append(dic) + # Handle total count for pagination context + total_count = All_Prescription.objects.filter(Q(user_id__icontains = search) | Q(details__icontains = search)).count() + # Calculate total number of pages + total_pages = (total_count + page_size_prescription - 1) // page_size_prescription # This ensures rounding up + prescContext = { + 'count': total_pages, + 'page': { + 'object_list': report, + 'number': current_page, + 'has_previous': current_page > 1, + 'has_next': current_page < total_pages, + 'previous_page_number': current_page - 1 if current_page > 1 else None, + 'next_page_number': current_page + 1 if current_page < total_pages else None, + } + } + return JsonResponse({'status':1,"presc_context":prescContext}) + elif 'search_view_stock' in request.POST: + search = request.POST.get('search_view_stock') + current_page_stock = 1 + page_size_stock = 2 + offset_stock = (current_page_stock - 1 )* page_size_stock + live_meds=[] + live=Stock_entry.objects.filter(Q(Expiry_date__gte=date.today()) & Q( Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).order_by('Expiry_date')[offset_stock:offset_stock + page_size_stock] + total_pages_stock = ( Stock_entry.objects.filter(Q(Expiry_date__gte=date.today()) & Q(Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).count() + page_size_stock - 1) // page_size_stock + for e in live: + obj={} + obj['id']=e.id + obj['medicine_id']=e.medicine_id.brand_name + obj['Expiry_date']=e.Expiry_date + obj['supplier']=e.supplier + try: + qty=Present_Stock.objects.get(stock_id=e).quantity + except: + qty=0 + obj['quantity']=qty + live_meds.append(obj) + stockContext = { + 'count_stock_view':total_pages_stock, + 'page_stock_view':{ + 'object_list': live_meds, + 'number': current_page_stock, + 'has_previous': current_page_stock > 1, + 'has_next': current_page_stock < total_pages_stock, + 'previous_page_number': current_page_stock - 1 if current_page_stock > 1 else None, + 'next_page_number': current_page_stock + 1 if current_page_stock < total_pages_stock else None, + } + } + return JsonResponse({'status':1,'stock_context':stockContext}) + elif 'search_view_expired' in request.POST: + search = request.POST.get('search_view_expired') + current_page_stock_expired = 1 + page_size_stock_expired = 2 + offset_stock_expired = (current_page_stock_expired - 1 )* page_size_stock_expired + expired=[] + expiredData=Stock_entry.objects.filter(Q(Expiry_date__lt=date.today())&Q( Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).order_by('Expiry_date')[offset_stock_expired:offset_stock_expired + page_size_stock_expired] + total_pages_stock_expired = ( Stock_entry.objects.filter(Q(Expiry_date__lt=date.today())&Q( Q(medicine_id__brand_name__icontains = search) | Q(supplier__icontains = search))).count() + page_size_stock_expired - 1) // page_size_stock_expired + for e in expiredData: + obj={} + obj['medicine_id']=e.medicine_id.brand_name + obj['Expiry_date']=e.Expiry_date + obj['supplier']=e.supplier + try: + qty=Present_Stock.objects.get(stock_id=e).quantity + except: + qty=0 + obj['quantity']=qty + expired.append(obj) + ExpiredstockContext = { + 'count_stock_expired':total_pages_stock_expired, + 'page_stock_expired':{ + 'object_list': expired, + 'number': current_page_stock_expired, + 'has_previous': current_page_stock_expired > 1, + 'has_next': current_page_stock_expired < total_pages_stock_expired, + 'previous_page_number': current_page_stock_expired - 1 if current_page_stock_expired > 1 else None, + 'next_page_number': current_page_stock_expired + 1 if current_page_stock_expired < total_pages_stock_expired else None, + } + } + return JsonResponse({'status':1,'expired_context':ExpiredstockContext}) + elif 'search_view_required' in request.POST: + search = request.POST.get('search_view_required') + current_required_page = 1 + page_size_required = 2 + offset_stock_required = (current_required_page - 1 )* page_size_required + required_data = Required_medicine.objects.filter( Q(medicine_id__brand_name__icontains = search) )[offset_stock_required:offset_stock_required + page_size_required] + total_pages_stock_required = (Required_medicine.objects.filter( Q(medicine_id__brand_name__icontains = search) ).count() + page_size_required -1) // page_size_required + required=[] + for e in required_data: + obj={} + obj['medicine_id']=e.medicine_id.brand_name + obj['quantity']=e.quantity + obj['threshold'] = e.threshold + required.append(obj) + stocks = { + "count_stock_required" : total_pages_stock_required, + "page_stock_required":{ + "object_list":required, + 'number' : current_required_page, + 'has_previous' : current_required_page > 1 , + 'has_next': current_required_page < total_pages_stock_required, + 'previous_page_number' : current_required_page - 1 if current_required_page > 1 else None, + 'next_page_number' : current_required_page + 1 if current_required_page < total_pages_stock_required else None, + } + } + return JsonResponse({'status':1,'stocks':stocks}) + return JsonResponse({'status':1 , 'name':"bharadwaj"}) + +@api_view(['POST']) +def student_api_handler(request): + request_body = request.body.decode('utf-8') + request_body = json.loads(request_body) + if 'feed_submit' in request_body: + user_id = ExtraInfo.objects.select_related('user','department').get(user=request.user) + feedback = request_body['feedback'] + Complaint.objects.create( + user_id=user_id, + complaint=feedback, + date=datetime.now() + ) + data = {'status': 1} + healthcare_center_notif(request.user, request.user,'feedback_submitted','') + + return JsonResponse(data) + + elif 'medical_relief_submit' in request_body: + # print(request_body) + designation = request_body['designation'] + # print("# #") + # print(designation) + user=ExtraInfo.objects.get(pk=designation) + description = request_body['description'] + + # Retrieve the uploaded file from request.FILES + # uploaded_file = request.FILES.get('file') + + # Create an instance of the medical_relief model + form_object = medical_relief( + description=description, + # file=uploaded_file + ) + + # Save the form object + form_object.save() + + # Retrieve the form object you just saved + request_object = medical_relief.objects.get(pk=form_object.pk) + + # Retrieve HoldsDesignation instances + d = HoldsDesignation.objects.get(user__username=designation) + d1 = HoldsDesignation.objects.get(user__username=request.user) + + # Create a file entry using the create_file utility function + send_file_id = create_file( + uploader=request.user.username, + uploader_designation=request_body['selected_role'], + receiver=designation, + receiver_designation=d.designation, + src_module="health_center", + src_object_id=str(request_object.id), + file_extra_JSON={"value": 2}, + # attached_file=uploaded_file + ) + healthcare_center_notif(request.user,user.user,'rel_forward','') + request_object.file_id = send_file_id + request_object.save() + + # file_details_dict = view_file(file_id=send_file_id) + # print(file_details_dict) + return JsonResponse({'status': 1}) + + elif 'get_prescription' in request_body: + prescription_id = request_body['presc_id'] + prescription = All_Prescription.objects.get(id=prescription_id) + pre_medicine = All_Prescribed_medicine.objects.filter(prescription_id=prescription) + doctors=Doctor.objects.filter(active=True).order_by('id') + follow_presc =Prescription_followup.objects.filter(prescription_id=prescription).order_by('-id') + prescriptions=[] + for f_presc in follow_presc: + obj={} + obj['id'] = f_presc.id + obj['doctor'] = f_presc.Doctor_id.doctor_name + obj['diseaseDetails'] = f_presc.details + obj['followUpDate'] = f_presc.date + revoked=[] + for med in pre_medicine : + if med.revoked == True and med.revoked_prescription.id == f_presc.id : + obj1={} + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + revoked.append(obj1) + obj['revoked_medicines'] = revoked + presc_med = [] + for med in pre_medicine : + if med.prescription_followup_id == f_presc : + obj1={} + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + presc_med.append(obj1) + obj['medicines'] = presc_med + tests = "No Test suggested" + if f_presc.test!="" : + tests = f_presc.test + obj['tests'] = tests + obj['file_id'] = f_presc.file_id + prescriptions.append(obj) + obj={} + obj['id'] = 0 + obj['doctor'] = prescription.doctor_id.doctor_name + obj['diseaseDetails'] = prescription.details + obj['followUpDate'] = prescription.date + revoked=[] + obj['revoked_medicines'] = revoked + presc_med = [] + for med in pre_medicine : + if med.prescription_followup_id == None : + obj1={} + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + presc_med.append(obj1) + obj['medicines'] = presc_med + tests = "No Test suggested" + if prescription.test!="" : + tests = prescription.test + obj['tests'] = tests + obj['file_id'] = prescription.file_id + prescriptions.append(obj) + presc_serializer = serializers.PrescriptionSerializer(prescription) + + not_revoked=[] + for med in pre_medicine: + if med.revoked==False: + obj1={} + obj1['id'] = med.id + obj1['medicine'] = med.medicine_id.brand_name + obj1['quantity'] = med.quantity + obj1['days'] = med.days + obj1['times'] = med.times + not_revoked.append(obj1) + return JsonResponse({'status':1, 'prescription':presc_serializer.data, 'prescriptions':prescriptions , 'not_revoked' : not_revoked}) + + + elif 'acc_admin_forward' in request.POST: + file_id=request.POST['file_id'] + rec=File.objects.get(id=file_id) + des=Designation.objects.get(pk=rec.designation_id) + user=ExtraInfo.objects.get(pk=rec.uploader_id) + + forwarded_file_id=forward_file( + file_id=request.POST['file_id'], + receiver=rec.uploader_id, + receiver_designation=des.name, + file_extra_JSON= {"value": 2}, + remarks="Forwarded File with id: "+ str(request.POST['file_id'])+"to"+str(rec.id), + file_attachment=None, + ) + medical_relief_instance = medical_relief.objects.get(file_id=request.POST['file_id']) + medical_relief_instance.acc_admin_forward_flag = True + medical_relief_instance.save() + + healthcare_center_notif(request.user,user.user,'rel_approved','') + + return JsonResponse({'status':1}) + + elif 'announcement' in request.POST: + anno_id = request.POST.get('anno_id') + Announcements.objects.select_related('user_id','user_id__user','user_id__department', 'message', 'upload_announcement').filter(pk=anno_id).delete() + data = {'status': 1} + healthcare_center_notif(request.user,user.user,'new_announce','') + return JsonResponse({'status':1}) + + elif 'medical_profile' in request.POST: + user_id = request.POST.get('user_id') + MedicalProfile.objects.select_related('user_id','user_id__user','user_id__department', 'date_of_birth', 'gender', 'blood_type', 'height', 'weight').filter(pk=user_id).delete() + data = {'status': 1} + return JsonResponse({'status':1}) + elif 'datatype' in request_body and request_body['datatype'] == 'patientlog': + search = request_body['search_patientlog'] + print("patient") + page_size = 2 + new_current_page = int(request_body['page']) + new_offset = (new_current_page - 1) * page_size + new_report = [] + new_prescriptions = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).order_by('-date', '-id')[new_offset:new_offset + page_size] + total_count = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).count() + total_pages = (total_count + page_size - 1) // page_size + for pre in new_prescriptions: + doc = None + if pre.doctor_id != None : doc=pre.doctor_id.doctor_name + dic = { + 'id': pre.pk, + 'user_id': pre.user_id, + 'date': pre.date, + 'doctor_id':doc, + 'details': pre.details, + 'test': pre.test, + 'file_id': pre.file_id, + 'dependent_name':pre.dependent_name + # 'file': view_file(file_id=pre.file_id)['upload_file'] if pre.file_id else None + } + new_report.append(dic) + return JsonResponse({ + 'report': new_report, + 'page': new_current_page, + 'total_pages': total_pages, + 'has_previous': new_current_page > 1, + 'has_next': new_current_page < total_pages, + 'previous_page_number': new_current_page - 1 if new_current_page > 1 else None, + 'next_page_number': new_current_page + 1 if new_current_page < total_pages else None, + }) + elif 'search_patientlog' in request.POST: + search = request.POST.get('search_patientlog') + current_page = 1 + page_size_prescription = 2 # Default to 2 if not specified + offset = (current_page - 1) * page_size_prescription + prescriptions = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).order_by('-date', '-id')[offset:offset + page_size_prescription] + + report = [] + for pre in prescriptions: + doc = None + if pre.doctor_id != None : doc=pre.doctor_id.doctor_name + dic = { + 'id': pre.pk, + 'user_id': pre.user_id, + 'doctor_id': doc, + 'date': pre.date, + 'details': pre.details, + 'test': pre.test, + 'file_id': pre.file_id, + 'dependent_name':pre.dependent_name + # 'file': view_file(file_id=pre.file_id)['upload_file'] if pre.file_id else None + } + report.append(dic) + print(report) + # Handle total count for pagination context + total_count = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).count() + print(total_count) + # Calculate total number of pages + total_pages = (total_count + page_size_prescription - 1) // page_size_prescription # This ensures rounding up + prescContext = { + 'count': total_pages, + 'page': { + 'object_list': report, + 'number': current_page, + 'has_previous': current_page > 1, + 'has_next': current_page < total_pages, + 'previous_page_number': current_page - 1 if current_page > 1 else None, + 'next_page_number': current_page + 1 if current_page < total_pages else None, + } + } + return JsonResponse({'status':1,"presc_context":prescContext}) + elif "get_annoucements" in request_body: + announcements_data=Announcements.objects.all().order_by('-id').values() + serializer = serializers.AnnouncementSerializer(announcements_data,many=True) + return JsonResponse({'status':1, 'announcements' : serializer.data}) + elif "get_relief" in request_body: + uploader_outbox=view_outbox(username=request.user.username,designation=request_body['selected_role'] ,src_module='health_center') + medicalrelief=medical_relief.objects.all() + uploader_inbox=view_inbox(username=request.user.username,designation=request_body['selected_role'],src_module='health_center') + medicalRelief=[] + for out in uploader_outbox: + dic={} + + for mr in medicalrelief: + if mr.file_id==int(out['id']): + dic['id']=out['id'] + dic['upload_date']=datetime.fromisoformat(out['upload_date']).date() + dic['desc']=mr.description + # dic['file']=view_file(file_id=out['id'])['upload_file'] + dic['status']=mr.acc_admin_forward_flag + dic['approval_date']='' + + for inb in uploader_inbox: + if dic['id']==inb['id']: + dic['approval_date']=datetime.fromisoformat(inb['upload_date']).date() + medicalRelief.append(dic) + + return JsonResponse({'status':1, 'relief': medicalRelief}) + elif 'get_doctors' in request_body : + doctors = Doctor.objects.filter(active=True).order_by('id') + serializer = serializers.DoctorSerializer(doctors,many=True) + return JsonResponse({ 'status':1 , 'doctors':serializer.data }) + + elif 'get_pathologists' in request_body : + pathologists = Pathologist.objects.filter(active=True).order_by('id') + serializer = serializers.PathologistSerializer(pathologists,many=True) + return JsonResponse({'status':1,'pathologists':serializer.data}) + + elif 'get_doctor_schedule' in request_body : + # schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('day','doctor_id') + doctors=Doctor.objects.filter(active=True).order_by('id') + schedules = [] + for doctor in doctors : + obj1 = {} + schedule = Doctors_Schedule.objects.filter(doctor_id = doctor.id) + availability = [] + for sch in schedule : + obj = {} + obj['day'] = sch.day + obj['time'] = str(convert_to_am_pm(str(sch.from_time))) + "-" +str(convert_to_am_pm(str(sch.to_time))) + availability.append(obj) + obj1['name'] = doctor.doctor_name + obj1['specialization'] = doctor.specialization + obj1['availability'] = availability + schedules.append(obj1) + + return JsonResponse({ 'status':1, 'schedule':schedules }) + + elif 'get_pathologist_schedule' in request_body : + # schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('day','doctor_id') + pathologists=Pathologist.objects.filter(active=True).order_by('id') + schedules = [] + for pathologist in pathologists : + obj1 = {} + schedule = Pathologist_Schedule.objects.filter(pathologist_id = pathologist.id) + availability = [] + for sch in schedule : + obj = {} + obj['day'] = sch.day + obj['time'] = str(convert_to_am_pm(str(sch.from_time))) + "-" +str(convert_to_am_pm(str(sch.to_time))) + availability.append(obj) + obj1['name'] = pathologist.pathologist_name + obj1['specialization'] = pathologist.specialization + obj1['availability'] = availability + schedules.append(obj1) + + return JsonResponse({ 'status':1, 'schedule':schedules }) # def getDesignation(request): # user = request.user diff --git a/FusionIIIT/applications/health_center/migrations/0011_auto_20241015_1829.py b/FusionIIIT/applications/health_center/migrations/0011_auto_20241015_1829.py new file mode 100644 index 000000000..881708716 --- /dev/null +++ b/FusionIIIT/applications/health_center/migrations/0011_auto_20241015_1829.py @@ -0,0 +1,31 @@ +# Generated by Django 3.1.5 on 2024-10-15 18:29 + +import datetime +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('globals', '0002_auto_20241007_2302'), + ('health_center', '0010_auto_20240727_2352'), + ] + + operations = [ + migrations.AddField( + model_name='medical_relief', + name='compounder_reject_flag', + field=models.BooleanField(default=False), + ), + migrations.CreateModel( + name='Announcements', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('ann_date', models.DateTimeField(default=datetime.date.today)), + ('message', models.CharField(max_length=200)), + ('upload_announcement', models.FileField(default=' ', null=True, upload_to='health_center/upload_announcement')), + ('anno_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='announcements_made', to='globals.extrainfo')), + ], + ), + ] diff --git a/FusionIIIT/applications/health_center/migrations/0012_complaint.py b/FusionIIIT/applications/health_center/migrations/0012_complaint.py new file mode 100644 index 000000000..c79a409bd --- /dev/null +++ b/FusionIIIT/applications/health_center/migrations/0012_complaint.py @@ -0,0 +1,25 @@ +# Generated by Django 3.1.5 on 2024-10-18 00:00 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('globals', '0002_auto_20241007_2302'), + ('health_center', '0011_auto_20241015_1829'), + ] + + operations = [ + migrations.CreateModel( + name='Complaint', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('feedback', models.CharField(max_length=100, null=True)), + ('complaint', models.CharField(max_length=100, null=True)), + ('date', models.DateField(auto_now=True)), + ('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='globals.extrainfo')), + ], + ), + ] diff --git a/FusionIIIT/applications/health_center/models.py b/FusionIIIT/applications/health_center/models.py index 7f46307f0..c730dd285 100644 --- a/FusionIIIT/applications/health_center/models.py +++ b/FusionIIIT/applications/health_center/models.py @@ -2,6 +2,7 @@ from django.db import models from datetime import date from django.contrib.auth.models import User +import datetime from applications.globals.models import ExtraInfo from applications.hr2.models import EmpDependents @@ -48,12 +49,20 @@ class Pathologist(models.Model): def __str__(self): return self.pathologist_name + +class Announcements(models.Model): + anno_id = models.ForeignKey(ExtraInfo, on_delete=models.CASCADE, related_name='announcements_made') + ann_date = models.DateTimeField(default=datetime.date.today) + message = models.CharField(max_length=200) + upload_announcement = models.FileField(upload_to='health_center/upload_announcement', null=True, default=" ") + def __str__(self): + return str(self.anno_id.user.username) -# class Complaint(models.Model): -# user_id = models.ForeignKey(ExtraInfo,on_delete=models.CASCADE) -# feedback = models.CharField(max_length=100, null=True, blank=False) #This is the feedback given by the compounder -# complaint = models.CharField(max_length=100, null=True, blank=False) #Here Complaint given by user cannot be NULL! -# date = models.DateField(auto_now=True) +class Complaint(models.Model): + user_id = models.ForeignKey(ExtraInfo,on_delete=models.CASCADE) + feedback = models.CharField(max_length=100, null=True, blank=False) #This is the feedback given by the compounder + complaint = models.CharField(max_length=100, null=True, blank=False) #Here Complaint given by user cannot be NULL! + date = models.DateField(auto_now=True) class All_Medicine(models.Model): medicine_name = models.CharField(max_length=1000,default="NOT_SET", null=True) @@ -162,6 +171,7 @@ class medical_relief(models.Model): file_id=models.IntegerField(default=0) compounder_forward_flag = models.BooleanField(default=False) acc_admin_forward_flag = models.BooleanField(default=False) + compounder_reject_flag = models.BooleanField(default=False) class MedicalProfile(models.Model): diff --git a/FusionIIIT/applications/health_center/urls.py b/FusionIIIT/applications/health_center/urls.py index 982564fa2..8b7d19321 100644 --- a/FusionIIIT/applications/health_center/urls.py +++ b/FusionIIIT/applications/health_center/urls.py @@ -15,14 +15,16 @@ url(r'^compounder/view_file/(?P[\w-]+)/$',view_file, name='view_file'), url(r'^compounder/$', compounder_view, name='compounder_view'), url(r'^student/$', student_view, name='student_view'), - url(r'announcement/', announcement, name='announcement'), - url(r'medical_profile/', medical_profile, name='medical_profile'), + # url(r'announcement/', announcement, name='announcement'), + # url(r'medical_profile/', medical_profile, name='medical_profile'), + url(r'^student/view_prescription/(?P[0-9]+)/$',student_view_prescription,name='student_view_prescription'), + url(r'^compounder/view_relief/(?P[0-9]+)$',compounder_view_relief,name='view_relief'), #database entry url(r'^schedule_entry', schedule_entry, name='schedule_entry'), url(r'^doctor_entry', doctor_entry, name='doctor_entry'), url(r'^compounder_entry', compounder_entry, name='compounder_entry'), - # #api - # url(r'^api/',include('applications.health_center.api.urls')) + #api + url(r'^api/',include('applications.health_center.api.urls')) ] \ No newline at end of file diff --git a/FusionIIIT/applications/health_center/utils.py b/FusionIIIT/applications/health_center/utils.py index 220efea76..0006886f2 100644 --- a/FusionIIIT/applications/health_center/utils.py +++ b/FusionIIIT/applications/health_center/utils.py @@ -12,7 +12,7 @@ from .models import ( Doctor, Stock_entry,Present_Stock,All_Medicine, Doctors_Schedule,Pathologist_Schedule, Pathologist, medical_relief, MedicalProfile,All_Prescription,All_Prescribed_medicine, - Prescription_followup,files,Required_medicine) + Prescription_followup,files,Required_medicine,Announcements,Complaint) from applications.filetracking.sdk.methods import * from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import get_object_or_404 @@ -44,27 +44,6 @@ def compounder_view_handler(request): healthcare_center_notif(request.user, cmp.user, 'feedback_res','') return JsonResponse(data) - elif 'end' in request.POST: - pk = request.POST.get('id') - Ambulance_request.objects.select_related('user_id','user_id__user','user_id__department').filter(id=pk).update(end_date=datetime.now()) - amb=Ambulance_request.objects.select_related('user_id','user_id__user','user_id__department').filter(id=pk) - for f in amb: - dateo=f.end_date - data={'datenow':dateo} - return JsonResponse(data) - - # return expired medicine and update db - elif 'returned' in request.POST: - pk = request.POST.get('id') - Expiry.objects.select_related('medicine_id').filter(id=pk).update(returned=True,return_date=datetime.now()) - qty=Expiry.objects.select_related('medicine_id').get(id=pk).quantity - med=Expiry.objects.select_related('medicine_id').get(id=pk).medicine_id.id - quantity=Stock.objects.get(id=med).quantity - quantity=quantity-qty - Stock.objects.filter(id=med).update(quantity=quantity) - data={'status':1} - return JsonResponse(data) - # updating new doctor info in db elif 'add_doctor' in request.POST: doctor=request.POST.get('new_doctor') @@ -110,17 +89,7 @@ def compounder_view_handler(request): doc=Pathologist.objects.get(id=doctor).pathologist_name data={'status':1, 'id':doctor, 'doc':doc} return JsonResponse(data) - - # discharge patients - elif 'discharge' in request.POST: - pk = request.POST.get('discharge') - Hospital_admit.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').filter(id=pk).update(discharge_date=datetime.now()) - hosp=Hospital_admit.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').filter(id=pk) - for f in hosp: - dateo=f.discharge_date - data={'datenow':dateo, 'id':pk} - return JsonResponse(data) - + elif 'add_stock' in request.POST: try: medicine = request.POST.get('medicine_id') @@ -253,14 +222,11 @@ def compounder_view_handler(request): elif 'add_medicine' in request.POST: medicine = request.POST.get('new_medicine') - # quantity = request.POST.get('new_quantity') threshold = request.POST.get('threshold') brand_name = request.POST.get('brand_name') constituents = request.POST.get('constituents') manufacture_name = request.POST.get('manufacture_name') packsize = request.POST.get('packsize') - # new_supplier = request.POST.get('new_supplier') - # new_expiry_date = request.POST.get('new_expiry_date') tot_rows = All_Medicine.objects.all().count() All_Medicine.objects.create( id = tot_rows+1, @@ -271,69 +237,9 @@ def compounder_view_handler(request): manufacturer_name=manufacture_name, pack_size_label=packsize ) - # Stock.objects.create( - # medicine_name=medicine, - # quantity=quantity, - # threshold=threshold - # ) - # medicine_id = Stock.objects.get(medicine_name=medicine) - # Expiry.objects.create( - # medicine_id=medicine_id, - # quantity=quantity, - # supplier=new_supplier, - # expiry_date=new_expiry_date, - # returned=False, - # return_date=None, - # date=datetime.now() - # ) data = {'medicine': medicine, 'threshold': threshold,} return JsonResponse(data) - elif 'admission' in request.POST: - user = request.POST.get('user_id') - user_id = ExtraInfo.objects.select_related('user','department').get(id=user) - doctor = request.POST.get('doctor_id') - doctor_id = Doctor.objects.get(id=doctor) - admission_date = request.POST.get('admission_date') - reason = request.POST.get('description') - hospital_doctor = request.POST.get('hospital_doctor') - hospital_id = request.POST.get('hospital_name') - hospital_name = Hospital.objects.get(id=hospital_id) - Hospital_admit.objects.create( - user_id=user_id, - doctor_id=doctor_id, - hospital_name=hospital_name, - admission_date=admission_date, - hospital_doctor=hospital_doctor, - discharge_date=None, - reason=reason - ) - user=user_id.user - data={'status':1} - return JsonResponse(data) - - # elif 'medicine_name' in request.POST: - # app = request.POST.get('user') - # user = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').get(id=app).user_id - # quantity = int(request.POST.get('quantity')) - # days = int(request.POST.get('days')) - # times = int(request.POST.get('times')) - # medicine_id = request.POST.get('medicine_name') - # medicine = Stock.objects.get(id=medicine_id) - # Medicine.objects.create( - # patient=user, - # medicine_id=medicine, - # quantity=quantity, - # days=days, - # times=times - # ) - # user_medicine = Medicine.objects.filter(patient=user) - # list = [] - # for med in user_medicine: - # list.append({'medicine': med.medicine_id.medicine_name, 'quantity': med.quantity, - # 'days': med.days, 'times': med.times}) - # sches = json.dumps(list, default=datetime_handler) - # return HttpResponse(sches, content_type='json') elif 'get_stock' in request.POST: try: medicine_name_and_id = request.POST.get('medicine_name_for_stock') @@ -392,76 +298,6 @@ def compounder_view_handler(request): if quantity>qty : status=0 return JsonResponse({"status":status,"med_name":med_name,"id":id}) - # elif 'doct' in request.POST: - # doctor_id = request.POST.get('doct') - # schedule = Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id) - # list = [] - # for s in schedule: - # list.append({'room': s.room, 'id': s.id, 'doctor': s.doctor_id.doctor_name, - # 'day': s.get_day_display(), 'from_time': s.from_time, - # 'to_time': s.to_time}) - - # sches = json.dumps(list, default=datetime_handler) - # return HttpResponse(sches, content_type='json') - - elif 'prescribe' in request.POST: - app_id = request.POST.get('user') - details = request.POST.get('details') - tests = request.POST.get('tests') - appointment = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').get(id=app_id) - user=appointment.user_id - doctor=appointment.doctor_id - Prescription.objects.create( - user_id=user, - doctor_id=doctor, - details=details, - date=datetime.now(), - test=tests, - appointment=appointment - ) - query = Medicine.objects.select_related('patient','patient__user','patient__department').objects.filter(patient=user) - prescribe = Prescription.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','appointment','appointment__user_id','appointment__user_id__user','appointment__user_id__department','appointment__doctor_id','appointment__schedule','appointment__schedule__doctor_id').objects.all().last() - for medicine in query: - medicine_id = medicine.medicine_id - quantity = medicine.quantity - days = medicine.days - times = medicine.times - Prescribed_medicine.objects.create( - prescription_id=prescribe, - medicine_id=medicine_id, - quantity=quantity, - days=days, - times=times - ) - today=datetime.now() - expiry=Expiry.objects.select_related('medicine_id').filter(medicine_id=medicine_id,quantity__gt=0,returned=False,expiry_date__gte=today).order_by('expiry_date') - stock=Stock.objects.get(medicine_name=medicine_id).quantity - if stock>quantity: - for e in expiry: - q=e.quantity - em=e.id - if q>quantity: - q=q-quantity - Expiry.objects.select_related('medicine_id').filter(id=em).update(quantity=q) - qty = Stock.objects.get(medicine_name=medicine_id).quantity - qty = qty-quantity - Stock.objects.filter(medicine_name=medicine_id).update(quantity=qty) - break - else: - quan=Expiry.objects.select_related('medicine_id').get(id=em).quantity - Expiry.objects.select_related('medicine_id').filter(id=em).update(quantity=0) - qty = Stock.objects.get(medicine_name=medicine_id).quantity - qty = qty-quan - Stock.objects.filter(medicine_name=medicine_id).update(quantity=qty) - quantity=quantity-quan - status = 1 - else: - status = 0 - Medicine.objects.select_related('patient','patient__user','patient__department').all().delete() - - healthcare_center_notif(request.user, user.user, 'presc','') - data = {'status': status, 'stock': stock} - return JsonResponse(data) elif 'user_for_dependents' in request.POST: user = request.POST.get('user_for_dependents') if not User.objects.filter(username__iexact = user).exists(): @@ -497,9 +333,7 @@ def compounder_view_handler(request): new_file=files.objects.create( file_data=f ) - fid=new_file.id - # with open(uploaded_file.name, 'wb+') as destination: - # destination.write(f) + fid=new_file.id if is_dependent == "self": pres=All_Prescription.objects.create( user_id = user_id, @@ -521,20 +355,6 @@ def compounder_view_handler(request): dependent_relation = request.POST.get('dependent_relation'), file_id=fid ) - # designation=request.POST.get('user') - # d = HoldsDesignation.objects.get(user__username=designation) - # send_file_id = create_file( - # uploader=request.user.username, - # uploader_designation=request.session['currentDesignationSelected'], - # receiver=designation, - # receiver_designation=d.designation, - # src_module="health_center", - # src_object_id=str(pres.id), - # file_extra_JSON={"value": 2}, - # attached_file=uploaded_file - # ) - # pres.file_id=send_file_id - # pres.save() pre_medicine = request.POST.get('pre_medicine') @@ -582,75 +402,9 @@ def compounder_view_handler(request): else : Required_medicine.objects.create( medicine_id = med_id, - quantiy = qty, + quantity = qty, threshold = med_id.threshold ) - # pre_medicine = request.POST.get_json('pre_medicine') - # print(pre_medicine) - # details = request.POST.get('details') - # tests = request.POST.get('tests') - # # app = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(user_id=user_id,date=datetime.now()) - # # if app: - # # appointment = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').get(user_id=user_id,date=datetime.now()) - # # else: - # # appointment = None - # form_object=Prescription( - # user_id=user, - # doctor_id=doctor, - # details=details, - # date=datetime.now(), - # test=tests, - # # appointment=appointment - # ) - # form_object.save() - - # request_object.save() - - # query = Medicine.objects.select_related('patient','patient__user','patient__department').filter(patient=user) - # prescribe = Prescription.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').all().last() - # for medicine in query: - # medicine_id = medicine.medicine_id - # quantity = medicine.quantity - # days = medicine.days - # times = medicine.times - # Prescribed_medicine.objects.create( - # prescription_id=prescribe, - # medicine_id=medicine_id, - # quantity=quantity, - # days=days, - # times=times - # ) - # today=datetime.now() - # expiry=Expiry.objects.select_related('medicine_id').filter(medicine_id=medicine_id,quantity__gt=0,returned=False,expiry_date__gte=today).order_by('expiry_date') - # stock=Stock.objects.get(medicine_name=medicine_id).quantity - # if stock>quantity: - # for e in expiry: - # q=e.quantity - # em=e.id - # if q>quantity: - # q=q-quantity - # Expiry.objects.select_related('medicine_id').filter(id=em).update(quantity=q) - # qty = Stock.objects.get(medicine_name=medicine_id).quantity - # qty = qty-quantity - # Stock.objects.filter(medicine_name=medicine_id).update(quantity=qty) - # break - # else: - # quan=Expiry.objects.select_related('medicine_id').get(id=em).quantity - # Expiry.objects.select_related('medicine_id').filter(id=em).update(quantity=0) - # qty = Stock.objects.get(medicine_name=medicine_id).quantity - # qty = qty-quan - # Stock.objects.filter(medicine_name=medicine_id).update(quantity=qty) - # quantity=quantity-quan - # status = 1 - - # else: - # status = 0 - # Medicine.objects.select_related('patient','patient__user','patient__department').all().delete() - - - # healthcare_center_notif(request.user, user.user, 'presc','') - # data = {'status': status} - # return JsonResponse(data) return JsonResponse({"status":1}) elif 'presc_followup' in request.POST: @@ -810,15 +564,6 @@ def compounder_view_handler(request): except Exception as e: return JsonResponse({"status":0}) - elif 'cancel_presc' in request.POST: - presc_id = request.POST.get('cancel_presc') - prescription=Prescription.objects.get(pk=presc_id) - is_deleted = delete_file(file_id=prescription.file_id) - prescription.delete() - - - data = {'status': 1} - return JsonResponse(data) elif 'medicine' in request.POST: med_id = request.POST.get('medicine') try: @@ -847,6 +592,17 @@ def compounder_view_handler(request): healthcare_center_notif(request.user,user.user,'rel_approve','') data = {'status': 1} return JsonResponse(data) + elif 'compounder_reject' in request.POST: + file_id = request.POST.get('file_id') + relief = medical_relief.objects.get(file_id=file_id) + relief.compounder_reject_flag = True + relief.save() + rejected_user = request.POST.get('rejected_user') + user=User.objects.get(username__iexact = rejected_user) + rejected_user_info = ExtraInfo.objects.get(user_id = user) + healthcare_center_notif(request.user,rejected_user_info.user,'reject_relief','') + data = {'status': 1} + return JsonResponse(data) elif 'comp_announce' in request.POST: usrnm = get_object_or_404(User, username=request.user.username) user_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() @@ -861,7 +617,9 @@ def compounder_view_handler(request): formObject. upload_announcement = request.FILES.get('upload_announcement') formObject.ann_date = date.today() formObject.save() - healthcare_center_notif(usrnm, recipients , 'new_announce',formObject.message ) + print("before") + healthcare_center_notif(usrnm, recipients , 'new_announce',formObject.message ) + print("after") data = {'status': 1} return JsonResponse(data) elif 'datatype' in request.POST and request.POST['datatype'] == 'patientlog': @@ -1106,77 +864,9 @@ def compounder_view_handler(request): return JsonResponse({'status':1,'stocks':stocks}) def student_view_handler(request): - if 'amb_submit' in request.POST: - user_id = ExtraInfo.objects.select_related('user','department').get(user=request.user) - comp_id = ExtraInfo.objects.select_related('user','department').filter(user_type='compounder') - reason = request.POST.get('reason') - start_date = request.POST.get('start_date') - end_date = request.POST.get('end_date') - if end_date == '': - end_date = None - Ambulance_request.objects.create( - user_id=user_id, - date_request=datetime.now(), - start_date=start_date, - end_date=end_date, - reason=reason - ) - data = {'status': 1} - healthcare_center_notif(request.user, request.user, 'amb_request','') - for cmp in comp_id: - healthcare_center_notif(request.user, cmp.user, 'amb_req','') - - return JsonResponse(data) - elif "amb_submit1" in request.POST: - user_id = ExtraInfo.objects.select_related('user','department').get(user=request.user) - comp_id = ExtraInfo.objects.select_related('user','department').filter(user_type='compounder') - doctor_id = request.POST.get('doctor') - doctor = Doctor.objects.get(id=doctor_id) - date = request.POST.get('date') - schedule = Schedule.objects.select_related('doctor_id').get(id=date) - datei = schedule.date - app_time = schedule.to_time - description = request.POST.get('description') - Appointment.objects.create( - user_id=user_id, - doctor_id=doctor, - description=description, - schedule=schedule, - date=datei - ) - data = { - 'app_time': app_time, 'dt': datei , 'status' : 1 - } - healthcare_center_notif(request.user, request.user, 'appoint','') - for cmp in comp_id: - healthcare_center_notif(request.user, cmp.user, 'appoint_req','') - - return JsonResponse(data) - - - elif 'doctor' in request.POST: - doctor_id = request.POST.get('doctor') - days =Dotors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id).values('day') - today = datetime.today() - time = datetime.today().time() - sch = Doctors_Schedule.objects.select_related('doctor_id').filter(date__gte=today) - - for day in days: - for i in range(0, 7): - date = (datetime.today()+timedelta(days=i)).date() - dayi = date.weekday() - d = day.get('day') - if dayi == d: - - Doctors_Schedule.objects.select_related('doctor_id').filter(doctor_id=doctor_id, day=dayi).update(date=date) - - sch.filter(date=today, to_time__lt=time).delete() - schedule = sch.filter(doctor_id=doctor_id).order_by('date') - schedules = serializers.serialize('json', schedule) - return HttpResponse(schedules, content_type='json') - elif 'feed_submit' in request.POST: + if 'feed_submit' in request.POST: user_id = ExtraInfo.objects.select_related('user','department').get(user=request.user) feedback = request.POST.get('feedback') Complaint.objects.create( @@ -1188,17 +878,7 @@ def student_view_handler(request): healthcare_center_notif(request.user, request.user,'feedback_submitted','') return JsonResponse(data) - - elif 'cancel_amb' in request.POST: - amb_id = request.POST.get('cancel_amb') - Ambulance_request.objects.select_related('user_id','user_id__user','user_id__department').filter(pk=amb_id).delete() - data = {'status': 1} - return JsonResponse(data) - elif 'cancel_app' in request.POST: - app_id = request.POST.get('cancel_app') - Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(pk=app_id).delete() - data = {'status': 1} - return JsonResponse(data) + elif 'medical_relief_submit' in request.POST: designation = request.POST.get('designation') # print("# #") @@ -1224,6 +904,7 @@ def student_view_handler(request): # Retrieve HoldsDesignation instances d = HoldsDesignation.objects.get(user__username=designation) d1 = HoldsDesignation.objects.get(user__username=request.user) + print(request.session['currentDesignationSelected']) # Create a file entry using the create_file utility function send_file_id = create_file( @@ -1277,4 +958,77 @@ def student_view_handler(request): user_id = request.POST.get('user_id') MedicalProfile.objects.select_related('user_id','user_id__user','user_id__department', 'date_of_birth', 'gender', 'blood_type', 'height', 'weight').filter(pk=user_id).delete() data = {'status': 1} - return JsonResponse({'status':1}) \ No newline at end of file + return JsonResponse({'status':1}) + elif 'datatype' in request.POST and request.POST['datatype'] == 'patientlog': + search = request.POST.get('search_patientlog') + print("patient") + page_size = 2 + new_current_page = int(request.POST.get('page')) + new_offset = (new_current_page - 1) * page_size + new_report = [] + new_prescriptions = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).order_by('-date', '-id')[new_offset:new_offset + page_size] + total_count = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).count() + total_pages = (total_count + page_size - 1) // page_size + for pre in new_prescriptions: + doc = None + if pre.doctor_id != None : doc=pre.doctor_id.doctor_name + dic = { + 'id': pre.pk, + 'user_id': pre.user_id, + 'date': pre.date, + 'doctor_id':doc, + 'details': pre.details, + 'test': pre.test, + 'file_id': pre.file_id, + 'dependent_name':pre.dependent_name + # 'file': view_file(file_id=pre.file_id)['upload_file'] if pre.file_id else None + } + new_report.append(dic) + return JsonResponse({ + 'report': new_report, + 'page': new_current_page, + 'total_pages': total_pages, + 'has_previous': new_current_page > 1, + 'has_next': new_current_page < total_pages, + 'previous_page_number': new_current_page - 1 if new_current_page > 1 else None, + 'next_page_number': new_current_page + 1 if new_current_page < total_pages else None, + }) + elif 'search_patientlog' in request.POST: + search = request.POST.get('search_patientlog') + current_page = 1 + page_size_prescription = 2 # Default to 2 if not specified + offset = (current_page - 1) * page_size_prescription + prescriptions = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).order_by('-date', '-id')[offset:offset + page_size_prescription] + + report = [] + for pre in prescriptions: + doc = None + if pre.doctor_id != None : doc=pre.doctor_id.doctor_name + dic = { + 'id': pre.pk, + 'user_id': pre.user_id, + 'doctor_id': doc, + 'date': pre.date, + 'details': pre.details, + 'test': pre.test, + 'file_id': pre.file_id, + 'dependent_name':pre.dependent_name + # 'file': view_file(file_id=pre.file_id)['upload_file'] if pre.file_id else None + } + report.append(dic) + # Handle total count for pagination context + total_count = All_Prescription.objects.filter(Q(user_id__iexact = request.user.extrainfo.id) & Q( Q(user_id__icontains = search) | Q(details__icontains = search) | (Q(dependent_name__icontains = search)))).count() + # Calculate total number of pages + total_pages = (total_count + page_size_prescription - 1) // page_size_prescription # This ensures rounding up + prescContext = { + 'count': total_pages, + 'page': { + 'object_list': report, + 'number': current_page, + 'has_previous': current_page > 1, + 'has_next': current_page < total_pages, + 'previous_page_number': current_page - 1 if current_page > 1 else None, + 'next_page_number': current_page + 1 if current_page < total_pages else None, + } + } + return JsonResponse({'status':1,"presc_context":prescContext}) \ No newline at end of file diff --git a/FusionIIIT/applications/health_center/views.py b/FusionIIIT/applications/health_center/views.py index a178a9d68..fe637cd4a 100644 --- a/FusionIIIT/applications/health_center/views.py +++ b/FusionIIIT/applications/health_center/views.py @@ -17,7 +17,7 @@ from .models import ( Constants,All_Medicine,All_Prescribed_medicine,All_Prescription,Prescription_followup, Present_Stock,Doctor,Pathologist, Doctors_Schedule,Pathologist_Schedule,Stock_entry, - medical_relief,MedicalProfile,Required_medicine,files,Required_tabel_last_updated) + medical_relief,MedicalProfile,Required_medicine,files,Required_tabel_last_updated,Announcements,Complaint) from .utils import datetime_handler, compounder_view_handler, student_view_handler from applications.filetracking.sdk.methods import * from django.db.models import Q @@ -78,7 +78,7 @@ def compounder_view(request): else: notifs = request.user.notifications.all() - # all_complaints = Complaint.objects.select_related('user_id','user_id__user','user_id__department').all() + all_complaints = Complaint.objects.select_related('user_id','user_id__user','user_id__department').all().order_by('-id') # all_hospitals = Hospital_admit.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').all().order_by('-admission_date') # hospitals_list = Hospital.objects.all().order_by('hospital_name') # all_ambulances = Ambulance_request.objects.select_related('user_id','user_id__user','user_id__department').all().order_by('-date_request') @@ -90,6 +90,7 @@ def compounder_view(request): schedule1=Pathologist_Schedule.objects.select_related('pathologist_id').all().order_by('pathologist_id') # expired=Expiry.objects.select_related('medicine_id').filter(expiry_date__lt=datetime.now(),returned=False).order_by('expiry_date') # live_meds=Expiry.objects.select_related('medicine_id').filter(returned=False).order_by('quantity') + announcements_data=Announcements.objects.all().order_by('-id').values() page_size=2 fir=Required_tabel_last_updated.objects.first() if fir == None: @@ -280,15 +281,16 @@ def compounder_view(request): # dic['file']=view_file(file_id=ib['id'])['upload_file'] dic['status']=mr.compounder_forward_flag dic['status1']=mr.acc_admin_forward_flag + dic['status2']=mr.compounder_reject_flag inbox.append(dic) # print(inbox_files) return render(request, 'phcModule/phc_compounder.html', {'days': days, 'users': users,'expired':ExpiredstockContext, - 'stocks': stocks, + 'stocks': stocks,"all_complaints":all_complaints, 'doctors': doctors, 'pathologists':pathologists, - 'schedule': schedule, 'schedule1': schedule1, 'live_meds': stockContext, 'presc_hist': prescContext,'inbox_files':inbox,'medicines_presc':medicine_presc}) + 'schedule': schedule, 'schedule1': schedule1, 'live_meds': stockContext, 'presc_hist': prescContext,'inbox_files':inbox,'medicines_presc':medicine_presc,'announcements':announcements_data,}) else: return HttpResponseRedirect("/healthcenter/student") # compounder view ends @@ -323,10 +325,10 @@ def student_view(request): notifs = request.user.notifications.all() users = ExtraInfo.objects.all() user_id = ExtraInfo.objects.select_related('user','department').get(user=request.user) - hospitals = Hospital_admit.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').filter(user_id=user_id).order_by('-admission_date') - appointments = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(user_id=user_id).order_by('-date') - ambulances = Ambulance_request.objects.select_related('user_id','user_id__user','user_id__department').filter(user_id=user_id).order_by('-date_request') - announcements_data=Announcements.objects.all().values() + # hospitals = Hospital_admit.objects.select_related('user_id','user_id__user','user_id__department','doctor_id').filter(user_id=user_id).order_by('-admission_date') + # appointments = Appointment.objects.select_related('user_id','user_id__user','user_id__department','doctor_id','schedule','schedule__doctor_id').filter(user_id=user_id).order_by('-date') + # ambulances = Ambulance_request.objects.select_related('user_id','user_id__user','user_id__department').filter(user_id=user_id).order_by('-date_request') + announcements_data=Announcements.objects.all().order_by('-id').values() medical_profile=MedicalProfile.objects.filter(user_id=request.user.username) usrnm = get_object_or_404(User, username=request.user.username) user_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() @@ -343,8 +345,8 @@ def student_view(request): mp.append(dic) - medicines = Prescribed_medicine.objects.select_related('prescription_id','prescription_id__user_id','prescription_id__user_id__user','prescription_id__user_id__department','prescription_id__doctor_id','medicine_id').all() - complaints = Complaint.objects.select_related('user_id','user_id__user','user_id__department').filter(user_id=user_id).order_by('-date') + # medicines = Prescribed_medicine.objects.select_related('prescription_id','prescription_id__user_id','prescription_id__user_id__user','prescription_id__user_id__department','prescription_id__doctor_id','medicine_id').all() + # complaints = Complaint.objects.select_related('user_id','user_id__user','user_id__department').filter(user_id=user_id).order_by('-date') days = Constants.DAYS_OF_WEEK schedule=Doctors_Schedule.objects.select_related('doctor_id').all().order_by('doctor_id') schedule1=Pathologist_Schedule.objects.select_related('pathologist_id').all().order_by('pathologist_id') @@ -352,29 +354,29 @@ def student_view(request): pathologists=Pathologist.objects.filter(active=True) #prescription - prescription= Prescription.objects.filter(user_id=request.user.username) - report=[] - for pre in prescription: - dic={} - dic['id']=pre.id - dic['doctor_id'] = pre.doctor_id # Use dot notation - dic['date'] = pre.date # Use dot notation - dic['details'] = pre.details # Use dot notation - dic['test'] = pre.test # Use dot notation - if pre.file_id: - dic['file'] = view_file(file_id=pre.file_id)['upload_file'] - else: - dic['file']=None + # prescription= Prescription.objects.filter(user_id=request.user.username) + # report=[] + # for pre in prescription: + # dic={} + # dic['id']=pre.id + # dic['doctor_id'] = pre.doctor_id # Use dot notation + # dic['date'] = pre.date # Use dot notation + # dic['details'] = pre.details # Use dot notation + # dic['test'] = pre.test # Use dot notation + # if pre.file_id: + # dic['file'] = view_file(file_id=pre.file_id)['upload_file'] + # else: + # dic['file']=None - report.append(dic) + # report.append(dic) - count=Counter.objects.all() + # count=Counter.objects.all() - if count: - Counter.objects.all().delete() - Counter.objects.create(count=0,fine=0) - count=Counter.objects.get() + # if count: + # Counter.objects.all().delete() + # Counter.objects.create(count=0,fine=0) + # count=Counter.objects.get() designations = Designation.objects.filter() holdsDesignations = [] @@ -404,7 +406,25 @@ def student_view(request): uploader_inbox=view_inbox(username=request.user.username,designation=request.session['currentDesignationSelected'],src_module='health_center') medicalRelief=[] - + page_size =2 + current_page = 1 + page_size_prescription = page_size # Default to 2 if not specified + offset = (current_page - 1) * page_size_prescription + prescriptions = All_Prescription.objects.filter(user_id__iexact = request.user.extrainfo.id).order_by('-date', '-id')[offset:offset + page_size_prescription] + total_count = All_Prescription.objects.filter(user_id__iexact = request.user.extrainfo.id).count() + # Calculate total number of pages + total_pages = (total_count + page_size_prescription - 1) // page_size_prescription # This ensures rounding up + prescContext = { + 'count': total_pages, + 'page': { + 'object_list': prescriptions, + 'number': current_page, + 'has_previous': current_page > 1, + 'has_next': current_page < total_pages, + 'previous_page_number': current_page - 1 if current_page > 1 else None, + 'next_page_number': current_page + 1 if current_page < total_pages else None, + } + } for out in uploader_outbox: dic={} @@ -413,7 +433,7 @@ def student_view(request): dic['id']=out['id'] dic['upload_date']=datetime.fromisoformat(out['upload_date']).date() dic['desc']=mr.description - dic['file']=view_file(file_id=out['id'])['upload_file'] + # dic['file']=view_file(file_id=out['id'])['upload_file'] dic['status']=mr.acc_admin_forward_flag dic['approval_date']='' @@ -423,11 +443,14 @@ def student_view(request): medicalRelief.append(dic) + # return render(request, 'phcModule/phc_student.html', + # {'complaints': complaints, 'medicines': medicines, + # 'ambulances': ambulances, 'doctors': doctors, 'pathologists':pathologists, 'days': days,'count':count, + # 'hospitals': hospitals, 'appointments': appointments, + # 'prescription': report, 'schedule': schedule, 'schedule1': schedule1,'users': users, 'curr_date': datetime.now().date(),'holdsDesignations':holdsDesignations,'acc_admin_inbox':acc_ib,'medicalRelief':medicalRelief,'announcements':announcements_data,'medical_profile':mp}) return render(request, 'phcModule/phc_student.html', - {'complaints': complaints, 'medicines': medicines, - 'ambulances': ambulances, 'doctors': doctors, 'pathologists':pathologists, 'days': days,'count':count, - 'hospitals': hospitals, 'appointments': appointments, - 'prescription': report, 'schedule': schedule, 'schedule1': schedule1,'users': users, 'curr_date': datetime.now().date(),'holdsDesignations':holdsDesignations,'acc_admin_inbox':acc_ib,'medicalRelief':medicalRelief,'announcements':announcements_data,'medical_profile':mp}) + {'doctors': doctors, 'pathologists':pathologists, 'days': days,'prescription':prescriptions, + 'schedule': schedule, 'schedule1': schedule1,'users': users, 'curr_date': datetime.now().date(),'presc_hist': prescContext,'holdsDesignations':holdsDesignations,'acc_admin_inbox':acc_ib,'medicalRelief':medicalRelief,'medical_profile':mp,'announcements':announcements_data,}) else: return HttpResponseRedirect("/healthcenter/compounder") # student view ends @@ -464,15 +487,15 @@ def schedule_entry(request): to_time=time(y//3600,(y%3600)//60,y%60) print(to_time) room=int(z.cell(i,4).value) - u = Schedule.objects.create( - doctor_id = doc_id, - day = da, - from_time=from_time, - to_time=to_time, - room=room, - date=datetime.now() - ) - print("Schedule done -> ") + # u = Schedule.objects.create( + # doctor_id = doc_id, + # day = da, + # from_time=from_time, + # to_time=to_time, + # room=room, + # date=datetime.now() + # ) + # print("Schedule done -> ") except Exception as e: print(e) print(i) @@ -647,65 +670,65 @@ def browse_announcements(): return context -def get_to_request(username): - """ - This function is used to get requests for the receiver - - @variables: - req - Contains request queryset - - """ - req = SpecialRequest.objects.filter(request_receiver=username) - return req - - - -@login_required(login_url='/accounts/login') -def announcement(request): - """ - This function is contains data for Requests and Announcement Related methods. - Data is added to Announcement Table using this function. - - @param: - request - contains metadata about the requested page - - @variables: - usrnm, user_info, ann_anno_id - Stores data needed for maker - batch, programme, message, upload_announcement, - department, ann_date, user_info - Gets and store data from FORM used for Announcements for Students. - - """ - usrnm = get_object_or_404(User, username=request.user.username) - user_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() - num = 1 - ann_anno_id = user_info.id - requests_received = get_to_request(usrnm) - - if request.method == 'POST': - formObject = Announcements() - # formObject.key = Projects.objects.get(id=request.session['projectId']) - user_info = ExtraInfo.objects.all().select_related('user','department').get(id=ann_anno_id) - getstudents = ExtraInfo.objects.select_related('user') - recipients = User.objects.filter(extrainfo__in=getstudents) - # formObject.anno_id=1 - formObject.anno_id=user_info - # formObject.batch = request.POST['batch'] - # formObject.programme = request.POST['programme'] - formObject.message = request.POST['announcement'] - formObject. upload_announcement = request.FILES.get('upload_announcement') - # formObject.department = request.POST['department'] - formObject.ann_date = date.today() - #formObject.amount = request.POST['amount'] - formObject.save() - healthcare_center_notif(usrnm, recipients , 'new_announce',formObject.message ) - return redirect('../../compounder/') +# def get_to_request(username): +# """ +# This function is used to get requests for the receiver + +# @variables: +# req - Contains request queryset + +# """ +# # req = SpecialRequest.objects.filter(request_receiver=username) +# return req + + + +# @login_required(login_url='/accounts/login') +# def announcement(request): +# """ +# This function is contains data for Requests and Announcement Related methods. +# Data is added to Announcement Table using this function. + +# @param: +# request - contains metadata about the requested page + +# @variables: +# usrnm, user_info, ann_anno_id - Stores data needed for maker +# batch, programme, message, upload_announcement, +# department, ann_date, user_info - Gets and store data from FORM used for Announcements for Students. + +# """ +# usrnm = get_object_or_404(User, username=request.user.username) +# user_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() +# num = 1 +# ann_anno_id = user_info.id +# requests_received = get_to_request(usrnm) + +# if request.method == 'POST': +# formObject = Announcements() +# # formObject.key = Projects.objects.get(id=request.session['projectId']) +# user_info = ExtraInfo.objects.all().select_related('user','department').get(id=ann_anno_id) +# getstudents = ExtraInfo.objects.select_related('user') +# recipients = User.objects.filter(extrainfo__in=getstudents) +# # formObject.anno_id=1 +# formObject.anno_id=user_info +# # formObject.batch = request.POST['batch'] +# # formObject.programme = request.POST['programme'] +# formObject.message = request.POST['announcement'] +# formObject. upload_announcement = request.FILES.get('upload_announcement') +# # formObject.department = request.POST['department'] +# formObject.ann_date = date.today() +# #formObject.amount = request.POST['amount'] +# formObject.save() +# healthcare_center_notif(usrnm, recipients , 'new_announce',formObject.message ) +# return redirect('../../compounder/') - announcements_data=Announcements.objects.all().values() +# announcements_data=Announcements.objects.all().values() - return render(request, 'health_center/make_announce_comp.html', {"user_designation":user_info.user_type, - 'announcements':announcements_data, - "request_to":requests_received - }) +# return render(request, 'health_center/make_announce_comp.html', {"user_designation":user_info.user_type, +# 'announcements':announcements_data, +# "request_to":requests_received +# }) # batch = request.POST.get('batch', '') # programme = request.POST.get('programme', '') # message = request.POST.get('announcement', '') @@ -724,54 +747,54 @@ def announcement(request): # department = department, # ann_date=ann_date) -@login_required(login_url='/accounts/login') -def medical_profile(request): - usrnm = get_object_or_404(User, username=request.user.username) - user_id_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() - num = 1 - user_id = user_id_info.id - requests_received = get_to_request(usrnm) - user = request.user - # medical_profile, created = MedicalProfile.objects.get_or_create(user_id==request.user.username) - medical_profile=MedicalProfile.objects.filter(user_id=request.user.username) - usrnm = get_object_or_404(User, username=request.user.username) - user_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() - # mp=[]/ - cnt=0 - for mr in medical_profile: - cnt += 1 - if request.method == 'POST': - user_info = ExtraInfo.objects.all().select_related('user','department').get(id=user_id) +# @login_required(login_url='/accounts/login') +# def medical_profile(request): +# usrnm = get_object_or_404(User, username=request.user.username) +# user_id_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() +# num = 1 +# user_id = user_id_info.id +# # requests_received = get_to_request(usrnm) +# user = request.user +# # medical_profile, created = MedicalProfile.objects.get_or_create(user_id==request.user.username) +# medical_profile=MedicalProfile.objects.filter(user_id=request.user.username) +# usrnm = get_object_or_404(User, username=request.user.username) +# user_info = ExtraInfo.objects.all().select_related('user','department').filter(user=usrnm).first() +# # mp=[]/ +# cnt=0 +# for mr in medical_profile: +# cnt += 1 +# if request.method == 'POST': +# user_info = ExtraInfo.objects.all().select_related('user','department').get(id=user_id) - if cnt==0: - medical_profile = MedicalProfile() - medical_profile.user_id = user_info - medical_profile.date_of_birth = request.POST.get('date_of_birth') - medical_profile.gender = request.POST.get('gender') - medical_profile.blood_type = request.POST.get('blood_type') - medical_profile.height = request.POST.get('height') - medical_profile.weight = request.POST.get('weight') - # medical_profile.form_submitted = True - medical_profile.save() - return redirect('../../compounder/') +# if cnt==0: +# medical_profile = MedicalProfile() +# medical_profile.user_id = user_info +# medical_profile.date_of_birth = request.POST.get('date_of_birth') +# medical_profile.gender = request.POST.get('gender') +# medical_profile.blood_type = request.POST.get('blood_type') +# medical_profile.height = request.POST.get('height') +# medical_profile.weight = request.POST.get('weight') +# # medical_profile.form_submitted = True +# medical_profile.save() +# return redirect('../../compounder/') - else: - # Process the form submission for the first time - medical_profile1=MedicalProfile.objects.filter(user_id=user_info).first() +# else: +# # Process the form submission for the first time +# medical_profile1=MedicalProfile.objects.filter(user_id=user_info).first() - medical_profile1.date_of_birth = request.POST.get('date_of_birth') - medical_profile1.gender = request.POST.get('gender') - medical_profile1.blood_type = request.POST.get('blood_type') - medical_profile1.height = request.POST.get('height') - medical_profile1.weight = request.POST.get('weight') - # medical_profile.form_submitted = True - medical_profile1.save() - return redirect('../../compounder/') +# medical_profile1.date_of_birth = request.POST.get('date_of_birth') +# medical_profile1.gender = request.POST.get('gender') +# medical_profile1.blood_type = request.POST.get('blood_type') +# medical_profile1.height = request.POST.get('height') +# medical_profile1.weight = request.POST.get('weight') +# # medical_profile.form_submitted = True +# medical_profile1.save() +# return redirect('../../compounder/') - return render(request, 'health_center/medical_profile.html', {"user_designation":user_info.user_type, - 'medical_profile':medical_profile, - "request_to":requests_received - }) +# return render(request, 'health_center/medical_profile.html', {"user_designation":user_info.user_type, +# 'medical_profile':medical_profile, +# "request_to":requests_received +# }) @login_required def compounder_view_prescription(request,prescription_id): @@ -779,8 +802,6 @@ def compounder_view_prescription(request,prescription_id): pre_medicine = All_Prescribed_medicine.objects.filter(prescription_id=prescription) doctors=Doctor.objects.filter(active=True).order_by('id') follow_presc =Prescription_followup.objects.filter(prescription_id=prescription).order_by('-id') - if request.method == "POST": - print("post") return render(request, 'phcModule/phc_compounder_view_prescription.html',{'prescription':prescription, 'pre_medicine':pre_medicine,'doctors':doctors, "follow_presc":follow_presc}) @@ -805,3 +826,40 @@ def view_file(request,file_id): response['Content-Disposition'] = 'inline; filename="generated.pdf"' return response + +@login_required +def student_view_prescription(request,prescription_id): + prescription = All_Prescription.objects.get(id=prescription_id) + pre_medicine = All_Prescribed_medicine.objects.filter(prescription_id=prescription) + doctors=Doctor.objects.filter(active=True).order_by('id') + follow_presc =Prescription_followup.objects.filter(prescription_id=prescription).order_by('-id') + return render(request, 'phcModule/phc_student_view_prescription.html',{'prescription':prescription, + 'pre_medicine':pre_medicine,'doctors':doctors, + "follow_presc":follow_presc}) + +@login_required +def compounder_view_relief(request,relief_id): + inbox_files=view_inbox(username=request.user.username,designation='Compounder',src_module='health_center') + medicalrelief=medical_relief.objects.all() + + inbox=[] + for ib in inbox_files: + if int(ib['id']) == int(relief_id) : + dic={} + for mr in medicalrelief: + if mr.file_id==int(ib['id']): + dic['id']=ib['id'] + dic['uploader']=ib['uploader'] + dic['upload_date']=datetime.fromisoformat(ib['upload_date']).date() + dic['desc']=mr.description + # dic['file']=view_file(file_id=ib['id'])['upload_file'] + status = "Pending" + if mr.acc_admin_forward_flag : + status = "Approved" + elif mr.compounder_forward_flag : + status = "Forwarded" + elif mr.compounder_reject_flag : + status = "Rejected" + dic['status']=status + inbox.append(dic) + return render(request,'phcModule/phc_compounder_view_relief.html',{'inbox':inbox[0],}) \ No newline at end of file diff --git a/FusionIIIT/applications/programme_curriculum/forms.py b/FusionIIIT/applications/programme_curriculum/forms.py index 394828004..d6c8a53e0 100644 --- a/FusionIIIT/applications/programme_curriculum/forms.py +++ b/FusionIIIT/applications/programme_curriculum/forms.py @@ -8,7 +8,7 @@ from django.contrib.auth.models import User from applications.globals.models import (DepartmentInfo, Designation,ExtraInfo, Faculty, HoldsDesignation) from applications.filetracking.sdk.methods import * - +from django.db.models import Q class ProgrammeForm(ModelForm): class Meta: @@ -38,6 +38,20 @@ class Meta: 'programmes': 'Link Programmes to this Disciplines', 'acronym' : 'Enter Acronym' } + def __init__(self, *args, **kwargs): + super(DisciplineForm, self).__init__(*args, **kwargs) + + # Get the current discipline instance + discipline = kwargs.get('instance', None) + + if discipline: + # Show programmes that are either unlinked or linked to the current discipline + self.fields['programmes'].queryset = Programme.objects.filter( + Q(discipline__isnull=True) | Q(discipline=discipline) + ) + else: + # Show only programmes that are unlinked (no discipline assigned) + self.fields['programmes'].queryset = Programme.objects.filter(discipline__isnull=True) class CurriculumForm(ModelForm): @@ -203,6 +217,18 @@ class Meta: 'year' : 'Batch Year', 'curriculum' : 'Select Curriculum For Batch Students', } + def __init__(self, *args, **kwargs): + super(BatchForm, self).__init__(*args, **kwargs) + + # Get the list of curriculum ids that are already assigned to batches (excluding NULL values) + assigned_curriculum_ids = Batch.objects.filter(curriculum__isnull=False).values_list('curriculum', flat=True) + + # Exclude curriculums already in use + available_curriculums = Curriculum.objects.exclude(id__in=assigned_curriculum_ids) + + # Add an empty option (blank choice) at the start of the curriculum choices + self.fields['curriculum'].queryset = available_curriculums + self.fields['curriculum'].empty_label = "Select Curriculum" # This adds a blank option with a label class CourseSlotForm(ModelForm): diff --git a/FusionIIIT/applications/programme_curriculum/views.py b/FusionIIIT/applications/programme_curriculum/views.py index e0fdb5a50..602bbc866 100644 --- a/FusionIIIT/applications/programme_curriculum/views.py +++ b/FusionIIIT/applications/programme_curriculum/views.py @@ -439,7 +439,7 @@ def admin_view_semesters_of_a_curriculum(request, curriculum_id): transpose_semester_slots = list(zip(*semester_slots)) - all_batches = Batch.objects.filter(running_batch=True).exclude(curriculum=curriculum_id).order_by('year') + all_batches = Batch.objects.filter(running_batch=True, curriculum__isnull=True).order_by('year') return render(request, 'programme_curriculum/acad_admin/admin_view_semesters_of_a_curriculum.html', {'curriculum': curriculum, 'semesters': semesters, 'semester_slots': transpose_semester_slots, 'semester_credits': semester_credits, 'all_batches':all_batches}) @@ -925,29 +925,32 @@ def delete_courseslot(request, courseslot_id): return render(request, 'programme_curriculum/view_a_courseslot.html', {'course_slot': courseslot}) +# views.py def add_batch_form(request): - - user_details = ExtraInfo.objects.get(user = request.user) - des = HoldsDesignation.objects.all().filter(user = request.user).first() - if request.session['currentDesignationSelected']== "student" or request.session['currentDesignationSelected']== "Associate Professor" or request.session['currentDesignationSelected']== "Professor" or request.session['currentDesignationSelected']== "Assistant Professor" : + user_details = ExtraInfo.objects.get(user=request.user) + des = HoldsDesignation.objects.all().filter(user=request.user).first() + + if request.session['currentDesignationSelected'] in ["student", "Associate Professor", "Professor", "Assistant Professor"]: return HttpResponseRedirect('/programme_curriculum/programmes/') - elif str(request.user) == "acadadmin" : + elif str(request.user) == "acadadmin": pass elif 'hod' in request.session['currentDesignationSelected'].lower(): return HttpResponseRedirect('/programme_curriculum/programmes/') - - curriculum_id = request.GET.get('curriculum_id', -1) - form = BatchForm(initial={'curriculum': curriculum_id}) - submitbutton= request.POST.get('Submit') + + # Explicitly setting curriculum to None or '' to prevent any default value + form = BatchForm(initial={'curriculum': None}) + + submitbutton = request.POST.get('Submit') if submitbutton: if request.method == 'POST': form = BatchForm(request.POST) if form.is_valid(): form.save() - messages.success(request, "Added Batch successful") + messages.success(request, "Added Batch successfully") return HttpResponseRedirect('/programme_curriculum/admin_batches/') - return render(request, 'programme_curriculum/acad_admin/add_batch_form.html',{'form':form, 'submitbutton': submitbutton}) - + + return render(request, 'programme_curriculum/acad_admin/add_batch_form.html', {'form': form, 'submitbutton': submitbutton}) + def edit_batch_form(request, batch_id): diff --git a/FusionIIIT/notification/views.py b/FusionIIIT/notification/views.py index 5f134a9a7..479d1cf68 100644 --- a/FusionIIIT/notification/views.py +++ b/FusionIIIT/notification/views.py @@ -267,7 +267,9 @@ def healthcare_center_notif(sender, recipient, type, message): elif type == 'rel_approve': verb = "You have a new medical relief approval request" elif type == 'rel_approved': - verb = 'Your medical relief request has been approved' + verb = 'Your medical relief request has been approved' + elif type == 'reject_relief': + verb = "Your medical relief request has been rejected" notify.send(sender=sender, recipient=recipient, url=url, module=module, verb=verb, flag=flag) # send_notification_email.delay(recipient.username, recipient.email, verb, module) diff --git a/FusionIIIT/templates/phcModule/compounder_medical_relief.html b/FusionIIIT/templates/phcModule/compounder_medical_relief.html index f02f69ee5..e2ba0912c 100644 --- a/FusionIIIT/templates/phcModule/compounder_medical_relief.html +++ b/FusionIIIT/templates/phcModule/compounder_medical_relief.html @@ -24,13 +24,13 @@ Description - - - File - + Status - + + + view + @@ -48,26 +48,20 @@ {{ inbox.desc }} - - - - - - {% if inbox.status1 %} Approved {% elif inbox.status %} - Forwarded + Forwarded + {% elif inbox.status2 %} + Rejected {% else %} Pending {% endif %} - {% if not inbox.status %} - - {% endif %} + @@ -77,24 +71,6 @@ - diff --git a/FusionIIIT/templates/phcModule/feedback_student.html b/FusionIIIT/templates/phcModule/feedback_student.html index fc65d3d9d..41f6f5cc6 100644 --- a/FusionIIIT/templates/phcModule/feedback_student.html +++ b/FusionIIIT/templates/phcModule/feedback_student.html @@ -75,10 +75,6 @@ } }); - -{% comment %} if(trimfield(document.getElementById("feedback").value) == ''){alert("Please fill out the feedback!") document.getElementById("feedback").focus(); } {% endcomment %} - -

diff --git a/FusionIIIT/templates/phcModule/history.html b/FusionIIIT/templates/phcModule/history.html index f0c161c12..5c7ee8bc2 100644 --- a/FusionIIIT/templates/phcModule/history.html +++ b/FusionIIIT/templates/phcModule/history.html @@ -22,8 +22,13 @@
-

D - No.of days,    T - No.of times per day

- +
+
+
+ +
+
+
@@ -39,26 +44,16 @@

D - No.of days,    T - No.of times per day

Details - - - - + {% for pre in prescription %} @@ -79,33 +74,24 @@

{{pre.details}}

- - - {% endfor %}
- Test + Dependent - Report - - - - - - -
MedicineDT
+ View
- {{pre.test}} - - {% if pre.file != None %} - - - - {% endif %} + {{pre.dependent_name}} - - {% for medicine in medicines %} - {% if medicine.prescription_id.id == pre.id %} - - {% endif %} - {% endfor%} -
{{medicine.medicine_id}}{{medicine.days}}{{medicine.times}}
+
- -
+
+ {% comment %}
@@ -139,6 +125,7 @@

+ {% comment %} {% for ambulance in ambulances%} @@ -157,18 +144,45 @@

{{ambulance.end_date}} - + {% endfor %}

{% endcomment %} - + {% comment %}
@@ -386,11 +500,11 @@

- + {% endfor %} diff --git a/FusionIIIT/templates/phcModule/make_announce_comp.html b/FusionIIIT/templates/phcModule/make_announce_comp.html index b4c79242b..981acfb2d 100644 --- a/FusionIIIT/templates/phcModule/make_announce_comp.html +++ b/FusionIIIT/templates/phcModule/make_announce_comp.html @@ -54,10 +54,10 @@

{% endif %} diff --git a/FusionIIIT/templates/phcModule/phc_compounder.html b/FusionIIIT/templates/phcModule/phc_compounder.html index 575a3ce65..8609ec983 100644 --- a/FusionIIIT/templates/phcModule/phc_compounder.html +++ b/FusionIIIT/templates/phcModule/phc_compounder.html @@ -58,12 +58,10 @@ Doctors/Pathologists - Feedback/Response - - + Make Announcements diff --git a/FusionIIIT/templates/phcModule/phc_compounder_view_prescription.html b/FusionIIIT/templates/phcModule/phc_compounder_view_prescription.html index 0b77908ad..785532932 100644 --- a/FusionIIIT/templates/phcModule/phc_compounder_view_prescription.html +++ b/FusionIIIT/templates/phcModule/phc_compounder_view_prescription.html @@ -657,7 +657,6 @@ function view_report(f){ console.log(f.id) var pk=f.id - alert('view_report') var url= `{% url 'healthcenter:view_file' file_id='0' %}` var newurl=url.replace('0',f.id) window.open(newurl,"_blank") diff --git a/FusionIIIT/templates/phcModule/phc_compounder_view_relief.html b/FusionIIIT/templates/phcModule/phc_compounder_view_relief.html new file mode 100644 index 000000000..e8dcdd625 --- /dev/null +++ b/FusionIIIT/templates/phcModule/phc_compounder_view_relief.html @@ -0,0 +1,366 @@ +{% extends 'globals/base.html' %} +{% load static %} + +{% block title %} + Home +{% endblock %} + +{% block body %} + + + {% block navBar %} + {% include 'dashboard/navbar.html' %} + {% endblock %} + + {% comment %}The grid starts here!{% endcomment %} +
+ + {% comment %}The left-margin segment!{% endcomment %} +
+ + {% comment %}The left-rail segment starts here!{% endcomment %} +
+ {% comment %}The left-rail segment ends here!{% endcomment %} + + {% comment %}The central-rail segment starts here!{% endcomment %} +
+ + {% comment %}The ap `pointment approval tab starts here!{% endcomment %} +
+ + {% block patientlog %} +
+
+

{{inbox.uploader}}'s Relief form

+
+
+
+
+ + +
+
+
+ + + {% if inbox.status == "Pending" %} +
+
+
+ + +
+
+ + +
+
+
+ {% endif %} + +
+
+
+ +
+ + + {% endblock %} + + + + {% comment %}The central-rail segment ends here!{% endcomment %} + + {% comment %}The right-rail segment starts here!{% endcomment %} +
+ {% comment %}
+ {% block sidepanel %} {% include 'notifications/sidepanel.html' with notifications=notifications %} + {% endblock %} +
{% endcomment %} +
+ {% comment %}The right-rail segment ends here!{% endcomment %} + + +
+ {% comment %}The right-margin segment!{% endcomment %} +
+ +
+ {% comment %}The grid ends here!{% endcomment %} + + + + +{% endblock %} + +{% block javascript %} + + + + + + + +{% endblock %} \ No newline at end of file diff --git a/FusionIIIT/templates/phcModule/phc_student.html b/FusionIIIT/templates/phcModule/phc_student.html index d2f402a11..1816c9184 100644 --- a/FusionIIIT/templates/phcModule/phc_student.html +++ b/FusionIIIT/templates/phcModule/phc_student.html @@ -46,7 +46,6 @@ History - Feedback diff --git a/FusionIIIT/templates/phcModule/phc_student_view_prescription.html b/FusionIIIT/templates/phcModule/phc_student_view_prescription.html new file mode 100644 index 000000000..2447864ee --- /dev/null +++ b/FusionIIIT/templates/phcModule/phc_student_view_prescription.html @@ -0,0 +1,563 @@ +{% extends 'globals/base.html' %} +{% load static %} + +{% block title %} + Home +{% endblock %} + +{% block body %} + + + {% block navBar %} + {% include 'dashboard/navbar.html' %} + {% endblock %} + + {% comment %}The grid starts here!{% endcomment %} +
+ + {% comment %}The left-margin segment!{% endcomment %} +
+ + {% comment %}The left-rail segment starts here!{% endcomment %} +
+ {% comment %}The left-rail segment ends here!{% endcomment %} + + {% comment %}The central-rail segment starts here!{% endcomment %} +
+ + {% comment %}The ap `pointment approval tab starts here!{% endcomment %} +
+ + {% block patientlog %} +
+
+

{{prescription.user_id}}'s Prescription History

+
+
+
+
+ + +
+
+
+ + {% for f_pres in follow_presc %} + + {% endfor %} + +
+
+ +
+ + + {% endblock %} +
+ + + {% comment %}The central-rail segment ends here!{% endcomment %} + + {% comment %}The right-rail segment starts here!{% endcomment %} +
+ {% comment %}
+ {% block sidepanel %} {% include 'notifications/sidepanel.html' with notifications=notifications %} + {% endblock %} +
{% endcomment %} +
+ {% comment %}The right-rail segment ends here!{% endcomment %} + + +
+ {% comment %}The right-margin segment!{% endcomment %} +
+ +
+ {% comment %}The grid ends here!{% endcomment %} + + + + +{% endblock %} + +{% block javascript %} + + + + + + + +{% endblock %} \ No newline at end of file diff --git a/FusionIIIT/templates/phcModule/schedule.html b/FusionIIIT/templates/phcModule/schedule.html index b27306428..7d3bb4a02 100644 --- a/FusionIIIT/templates/phcModule/schedule.html +++ b/FusionIIIT/templates/phcModule/schedule.html @@ -456,7 +456,7 @@

{{s.day}}

csrfmiddlewaretoken: '{{ csrf_token }}', pathologist:$("#pathologist_a").val(), day:$("#day_a1").val(), - rmv:$("#rmv1").val() + rmv1:$("#rmv1").val() }, success: function(data){ alert("Removed schedule"); diff --git a/FusionIIIT/templates/programme_curriculum/acad_admin/admin_view_semesters_of_a_curriculum.html b/FusionIIIT/templates/programme_curriculum/acad_admin/admin_view_semesters_of_a_curriculum.html index 35f30d2d7..e41901709 100644 --- a/FusionIIIT/templates/programme_curriculum/acad_admin/admin_view_semesters_of_a_curriculum.html +++ b/FusionIIIT/templates/programme_curriculum/acad_admin/admin_view_semesters_of_a_curriculum.html @@ -25,7 +25,7 @@

{{ curriculum }}

Batches:     {% for batch in curriculum.batches.all %} - {{ batch }},     + {{ batch }} {% endfor %}

@@ -189,14 +189,30 @@

- -
NEW BATCH
- -
+
+ {% if curriculum.batches.count < 1 %} + + +
NEW BATCH
+ +
+ {% else %} + + +
BATCH ALREADY ATTACHED
+ +
+ {% endif %} +
+
@@ -228,6 +244,7 @@

+ {% if curriculum.batches.count < 1 %} + {% else %} + + {% endif %} diff --git a/FusionIIIT/templates/programme_curriculum/faculty/view_semesters_of_a_curriculum.html b/FusionIIIT/templates/programme_curriculum/faculty/view_semesters_of_a_curriculum.html index 2b8f7e5dc..78ab0b10b 100644 --- a/FusionIIIT/templates/programme_curriculum/faculty/view_semesters_of_a_curriculum.html +++ b/FusionIIIT/templates/programme_curriculum/faculty/view_semesters_of_a_curriculum.html @@ -25,7 +25,7 @@

{{ curriculum }}

Batches:     {% for batch in curriculum.batches.all %} - {{ batch }},     + {{ batch }} {% endfor %}

diff --git a/FusionIIIT/templates/programme_curriculum/view_semesters_of_a_curriculum.html b/FusionIIIT/templates/programme_curriculum/view_semesters_of_a_curriculum.html index f6e3bb580..37943388b 100644 --- a/FusionIIIT/templates/programme_curriculum/view_semesters_of_a_curriculum.html +++ b/FusionIIIT/templates/programme_curriculum/view_semesters_of_a_curriculum.html @@ -25,7 +25,7 @@

{{ curriculum }}

Batches:     {% for batch in curriculum.batches.all %} - {{ batch }},     + {{ batch }} {% endfor %}

diff --git a/Test/Fusion Automation Testing/.project b/Test/Fusion Automation Testing/.project index b9fd33417..163865e2a 100644 --- a/Test/Fusion Automation Testing/.project +++ b/Test/Fusion Automation Testing/.project @@ -20,4 +20,15 @@ org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature + + + 1729578277564 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + +