• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

gcivil-nyu-org / INT2-Monday-Spring2024-Team-1 / 600

06 Apr 2024 07:58PM UTC coverage: 91.189% (-2.7%) from 93.876%
600

Pull #178

travis-pro

web-flow
Merge 81edf2db7 into 0a5d89e03
Pull Request #178: Feat/rejection

16 of 53 new or added lines in 4 files covered. (30.19%)

5 existing lines in 1 file now uncovered.

1304 of 1430 relevant lines covered (91.19%)

0.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.45
/healthScore/views.py
1
from django.shortcuts import render, redirect, get_object_or_404
1✔
2
from django.http import HttpResponse
1✔
3
from django.http import JsonResponse
1✔
4
from django.utils import timezone
1✔
5
from datetime import datetime, timedelta
1✔
6
from django.contrib.auth import authenticate, login
1✔
7
from django.contrib.auth.decorators import login_required
1✔
8
from django.forms.models import model_to_dict
1✔
9
import json
1✔
10

11
from reportlab.lib.pagesizes import letter
1✔
12
from reportlab.platypus import (
1✔
13
    SimpleDocTemplate,
14
    Paragraph,
15
    Spacer,
16
    Table,
17
    TableStyle,
18
    Image,
19
)
20
from reportlab.lib.styles import getSampleStyleSheet
1✔
21
from reportlab.lib import colors
1✔
22
from reportlab.lib.enums import TA_RIGHT
1✔
23
from reportlab.lib.styles import ParagraphStyle
1✔
24

25
# To overcame issues with regards to permissions (POST calls will give CSRF errors if the below tag is not used)
26
from django.views.decorators.csrf import csrf_exempt
1✔
27

28
from .models import (
1✔
29
    Appointment,
30
    HealthRecord,
31
    Hospital,
32
    User,
33
    HospitalStaff,
34
    Post,
35
    Comment,
36
    HealthHistoryAccessRequest,
37
)
38

39
from .user_utils import get_health_history_details
1✔
40
from .forms import PostForm, CommentForm
1✔
41
from .file_upload import file_upload
1✔
42
from django.core.mail import send_mail
1✔
43

44

45
DATE_FORMAT = "%Y-%m-%d"
1✔
46
APPOINTMENT_TYPE = {
1✔
47
    "blood_test": "Blood Test",
48
    "eye": "Eye Exams",
49
    "general": "General Physical",
50
    "dermatologist": "Dermatologist",
51
    "diabetes_screening": "Diabetes Screening",
52
    "dentist": "Dentist",
53
    "gynecologist": "Gynecologist",
54
    "vaccinations": "Vaccinations",
55
}
56

57
APPOINTMENT_PROPS = {
1✔
58
    "blood_test": {
59
        "blood_group": "Blood Group",
60
        "hemoglobin_count": "Hemoglobin Count",
61
        "date": "Date",
62
        "platelet_count": "Platelet Count",
63
    },
64
    "eye": {
65
        "cylindrical_power_right": "Cylindrical Power Right",
66
        "cylindrical_power_left": "Cylindrical Power Left",
67
        "spherical_power_left": "Spherical Power Left",
68
        "spherical_power_right": "Spherical Power Right",
69
        "date": "Date",
70
    },
71
    "general": {
72
        "blood_pressure": "Blood Pressure",
73
        "pulse_rate": "Pulse Rate",
74
        "date": "Date",
75
    },
76
    "dermatologist": {
77
        "care_received": "Care Received",
78
        "second_visit": "Second Visit Required",
79
        "date": "Date",
80
    },
81
    "diabetes_screening": {
82
        "fasting_sugar_level": "Fasting Sugar Level",
83
        "random_sugar_level": "Random Sugar Level",
84
        "second_visit": "Second Visit Required",
85
        "date": "Date",
86
    },
87
    "dentist": {
88
        "care_received": "Care Received",
89
        "second_visit": "Second Visit Required",
90
        "date": "Date",
91
    },
92
    "gynecologist": {
93
        "care_received": "Care Received",
94
        "second_visit": "Second Visit Required",
95
        "date": "Date",
96
    },
97
    "vaccinations": {
98
        "name": "Name",
99
        "type": "Vaccination Type",
100
        "dose_2": "Dose 2",
101
        "date": "Dose 2 Date",
102
    },
103
}
104

105

106
def homepage(request):
1✔
107
    return render(request, "homepage.html")
1✔
108

109

110
@login_required
1✔
111
def view_health_history(request):
1✔
112
    # Create a new QueryDict object with the desired parameters: fetch only approved records for health history page
113
    updated_params = request.GET.copy()
1✔
114
    updated_params["record_status"] = "approved"
1✔
115

116
    # Update request.GET with the modified QueryDict
117
    request.GET = updated_params
1✔
118

119
    zipped_details = get_health_history_details(request=request)
1✔
120
    return render(request, "view_history.html", {"zipped_details": zipped_details})
1✔
121

122

123
@login_required
1✔
124
def view_user_info(request):
1✔
125
    if request.method == "GET":
1✔
126
        current_user = request.user
1✔
127
        userInfo = {
1✔
128
            "email": current_user.email,
129
            "name": current_user.name,
130
            "dob": current_user.dob,
131
            "contactInfo": current_user.contactInfo,
132
            # dummy string for now. Needs to be replaced with the S3 string
133
            "proofOfIdentity": current_user.proofOfIdentity,
134
            "address": current_user.address,
135
            "gender": current_user.gender,
136
            "profilePic": current_user.profilePic,
137
            "bloodGroup": current_user.bloodGroup,
138
            "requests": json.dumps(current_user.requests),
139
        }
140

141
        try:
1✔
142
            hospital_staff = HospitalStaff.objects.get(userID=current_user.id)
1✔
143
            userInfo["specialization"] = hospital_staff.specialization
1✔
144
        except HospitalStaff.DoesNotExist:
×
145
            userInfo["specialization"] = "None"
×
146

147
        return render(request, "user_profile.html", {"userInfo": userInfo})
1✔
148

149

150
@login_required
1✔
151
@csrf_exempt
1✔
152
def edit_user_info(request):
1✔
153
    if request.method == "POST":
1✔
154
        current_user = request.user
1✔
155

156
        new_email = request.POST.get("email")
1✔
157
        file_url = file_upload(request, "userProfile")
1✔
158
        if new_email and new_email != current_user.email:
1✔
159
            if (
×
160
                User.objects.exclude(id=current_user.id)
161
                .filter(email=new_email)
162
                .exists()
163
            ):
164
                return JsonResponse(
×
165
                    {
166
                        "error": "This email address is already being used by another account."
167
                    },
168
                    status=400,
169
                )
170

171
        data_updated = False
1✔
172

173
        for field in ["name", "email", "address", "contactInfo", "profilePic"]:
1✔
174
            new_value = request.POST.get(field)
1✔
175
            current_value = getattr(current_user, field)
1✔
176
            if new_value and new_value != current_value:
1✔
177
                if field == "profilePic":
×
178
                    setattr(current_user, field, file_url)
×
179
                setattr(current_user, field, new_value)
×
180
                data_updated = True
×
181

182
        new_specialization = request.POST.get("specialization")
1✔
183
        if new_specialization:
1✔
184
            try:
×
185
                hospital_staff = HospitalStaff.objects.get(userID=current_user.id)
×
186
                if hospital_staff.specialization != new_specialization:
×
187
                    hospital_staff.specialization = new_specialization
×
188
                    hospital_staff.save()
×
189
                    data_updated = True
×
190
            except HospitalStaff.DoesNotExist:
×
191
                pass
×
192

193
        if data_updated:
1✔
194
            current_user.save()
×
195
            return JsonResponse(
×
196
                {"message": "User information updated successfully"}, status=200
197
            )
198
        else:
199
            return JsonResponse({"message": "No data was changed."}, status=200)
1✔
200
    else:
201
        view_user_info(request)
×
202

203

204
@login_required
1✔
205
def view_report(request):
1✔
206
    if request.method == "POST":
1✔
207
        response = HttpResponse(content_type="application/pdf")
1✔
208
        response["Content-Disposition"] = 'attachment; filename="Report.pdf"'
1✔
209

210
        doc = SimpleDocTemplate(response, pagesize=letter)
1✔
211
        styles = getSampleStyleSheet()
1✔
212
        story = []
1✔
213

214
        title_style = styles["Title"]
1✔
215
        title = "Health Records Report"
1✔
216
        story.append(Paragraph(title, title_style))
1✔
217
        story.append(Spacer(1, 18))
1✔
218

219
        right_aligned_style = ParagraphStyle(
1✔
220
            "RightAligned", parent=styles["Normal"], alignment=TA_RIGHT
221
        )
222
        current_date = datetime.now().strftime(DATE_FORMAT)
1✔
223

224
        logo = "healthScore/static/HSlogo.jpg"
1✔
225
        logo_img = Image(logo, width=128, height=40)
1✔
226
        logo_and_date = [
1✔
227
            [logo_img, Paragraph("Date: " + current_date, right_aligned_style)]
228
        ]
229
        logo_and_date = Table(logo_and_date)
1✔
230
        logo_and_date.setStyle(
1✔
231
            TableStyle(
232
                [
233
                    ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
234
                    ("ALIGN", (1, 0), (1, 0), "RIGHT"),
235
                    ("BOTTOMPADDING", (0, 0), (-1, -1), 12),
236
                ]
237
            )
238
        )
239
        story.append(logo_and_date)
1✔
240
        user_info = request.user
1✔
241
        story.append(Paragraph("Name: " + user_info.name, styles["Normal"]))
1✔
242
        story.append(Paragraph("DOB: " + user_info.dob, styles["Normal"]))
1✔
243
        story.append(Paragraph("BloodGroup: " + user_info.bloodGroup, styles["Normal"]))
1✔
244
        story.append(Paragraph("Email: " + user_info.email, styles["Normal"]))
1✔
245
        story.append(Paragraph("Contact: " + user_info.contactInfo, styles["Normal"]))
1✔
246
        story.append(Paragraph("Address: " + user_info.address, styles["Normal"]))
1✔
247
        story.append(Spacer(1, 12))
1✔
248

249
        table_data = [
1✔
250
            [
251
                Paragraph("Reason for Visit"),
252
                Paragraph("Visit Details"),
253
                Paragraph("Healthcare Worker"),
254
                Paragraph("Healthcare Facility"),
255
                Paragraph("Address"),
256
                Paragraph("Date"),
257
                Paragraph("Properties"),
258
            ],
259
        ]
260

261
        selected_record_ids = request.POST.getlist("record_ids")
1✔
262
        for record_id in selected_record_ids:
1✔
263
            row = []
1✔
264
            record = HealthRecord.objects.get(id=record_id)
1✔
265
            appointment_pro = record.appointmentId.properties
1✔
266
            appointment_properties = json.loads(appointment_pro)
1✔
267
            appointment_name = record.appointmentId.name
1✔
268
            appointment_name_para = Paragraph(appointment_name)
1✔
269
            row.append(appointment_name_para)
1✔
270

271
            appointment_type = appointment_properties.get("type", "Unknown")
1✔
272
            appointment_type_para = Paragraph(appointment_type)
1✔
273
            row.append(appointment_type_para)
1✔
274

275
            doctor_name = HospitalStaff.objects.get(id=record.doctorID).name
1✔
276
            doctor_name_para = Paragraph(doctor_name)
1✔
277
            row.append(doctor_name_para)
1✔
278

279
            hospital_name = Hospital.objects.get(id=record.hospitalID).name
1✔
280
            hospital_name_para = Paragraph(hospital_name)
1✔
281
            row.append(hospital_name_para)
1✔
282

283
            hospital_addr = Hospital.objects.get(id=record.hospitalID).address
1✔
284
            hospital_addr_para = Paragraph(hospital_addr)
1✔
285
            row.append(hospital_addr_para)
1✔
286

287
            updated = record.updatedAt.strftime(DATE_FORMAT)
1✔
288
            updated_para = Paragraph(updated)
1✔
289
            row.append(updated_para)
1✔
290

291
            temp_row = []
1✔
292
            for rec, val in appointment_properties.items():
1✔
293
                if rec == "date":
1✔
294
                    val = datetime.strptime(val, "%Y-%m-%d %H:%M:%S.%f").strftime(
1✔
295
                        DATE_FORMAT
296
                    )
297

298
                temp_row.append(Paragraph(str(rec).capitalize() + " :   " + str(val)))
1✔
299
            row.append(temp_row)
1✔
300

301
            table_data.append(row)
1✔
302

303
        page_width, page_height = letter
1✔
304
        left_margin = right_margin = 50
1✔
305
        effective_page_width = page_width - (left_margin + right_margin)
1✔
306

307
        col_widths = [
1✔
308
            effective_page_width * 0.1,  # Reason for Visit
309
            effective_page_width * 0.15,  # Visit Details
310
            effective_page_width * 0.15,  # Healthcare Worker
311
            effective_page_width * 0.15,  # Healthcare Facility
312
            effective_page_width * 0.15,  # Address
313
            effective_page_width * 0.15,  # Date
314
            effective_page_width * 0.25,  # Properties
315
        ]
316
        table = Table(table_data, colWidths=col_widths)
1✔
317

318
        table_style = TableStyle(
1✔
319
            [
320
                ("BACKGROUND", (0, 0), (-1, 0), colors.grey),
321
                ("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
322
                ("ALIGN", (0, 0), (-1, -1), "CENTER"),
323
                ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
324
                ("BOTTOMPADDING", (0, 0), (-1, 0), 12),
325
                ("BACKGROUND", (0, 1), (-1, -1), colors.white),
326
                ("GRID", (0, 0), (-1, -1), 1, colors.black),
327
                ("TEXTCOLOR", (0, 0), (-1, -1), colors.black),
328
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
329
                ("WORDWRAP", (0, 0), (-1, -1), "CJK"),
330
            ]
331
        )
332

333
        table.setStyle(table_style)
1✔
334
        story.append(table)
1✔
335

336
        doc.build(story)
1✔
337
        return response
1✔
338

339

340
@csrf_exempt
1✔
341
def registration(request):
1✔
342
    if request.method == "POST":
1✔
343
        role = request.POST.get("role")
1✔
344
        email = request.POST.get("email")
1✔
345
        password = request.POST.get("password")
1✔
346
        fullname = request.POST.get("fullname")
1✔
347
        phone_number = request.POST.get("contactInfo")
1✔
348
        context = {"error_message:": ""}
1✔
349

350
        if User.objects.filter(email=email).exists():
1✔
351
            user = User.objects.get(email=email)
1✔
352
            if user.is_patient:
1✔
353
                context["error_message"] = (
1✔
354
                    "A patient account already exists with this email"
355
                )
356
            elif user.is_staff:
1✔
357
                context["error_message"] = (
1✔
358
                    "An admin account already exists with this email"
359
                )
360
            else:
361
                context["error_message"] = (
1✔
362
                    "A healthcare worker account already exists with this email"
363
                )
364

365
            return render(request, "registration.html", context)
1✔
366

367
        common_fields = {
1✔
368
            "email": email,
369
            "password": password,
370
            "name": fullname,
371
            "contactInfo": phone_number,
372
        }
373

374
        if role == "User":
1✔
375
            file_url = file_upload(request, "identityProof")
1✔
376
            user_specific_fields = {
1✔
377
                "dob": request.POST.get("dob"),
378
                "gender": request.POST.get("gender"),
379
                "address": f"{request.POST.get('street_address')}, {request.POST.get('city')}, {request.POST.get('state')}, {request.POST.get('zipcode')}",
380
                "proofOfIdentity": file_url,  # This needs handling for file upload
381
            }
382
            User.objects.create_patient(**common_fields, **user_specific_fields)
1✔
383

384
        elif role == "Healthcare Admin":
1✔
385
            hospital_name = request.POST.get("hospital_name")
1✔
386
            hospital_address = f"{request.POST.get('facility_street_address')}, {request.POST.get('facility_city')}, {request.POST.get('facility_state')}, {request.POST.get('facility_zipcode')}"
1✔
387

388
            user = User.objects.create_staff(**common_fields)
1✔
389

390
            hospital, created = Hospital.objects.get_or_create(
1✔
391
                name=hospital_name,
392
                defaults={"address": hospital_address, "contactInfo": phone_number},
393
            )
394

395
            HospitalStaff.objects.create(
1✔
396
                hospitalID=hospital,
397
                admin=True,
398
                name=fullname,
399
                contactInfo=phone_number,
400
                userID=user.id,
401
            )
402

403
        return redirect("homepage")
1✔
404

405
    return render(request, "registration.html")
1✔
406

407

408
def login_view(request):
1✔
409
    if request.method == "POST":
1✔
410
        email = request.POST.get("email")
1✔
411
        password = request.POST.get("password")
1✔
412

413
        user = authenticate(request, email=email, password=password, is_active=True)
1✔
414

415
        if user is not None:
1✔
416
            login(request, user)
1✔
417
            return redirect("homepage")
1✔
418
        else:
419
            return render(
1✔
420
                request,
421
                "login.html",
422
                {"error_message": "Invalid email or password. Please try again."},
423
            )
424
    return render(request, "login.html")
1✔
425

426

427
@login_required
1✔
428
def view_health_history_requests(request):
1✔
429
    zipped_details = get_health_history_details(request=request)
1✔
430
    return render(request, "view_requests.html", {"zipped_details": zipped_details})
1✔
431

432

433
@login_required
1✔
434
def record_sent_view(request):
1✔
435
    return render(request, "record_submit_complete.html")
1✔
436

437

438
def get_doctors(request, hos_id):
1✔
439
    doctorList = list(
1✔
440
        HospitalStaff.objects.filter(admin=False, hospitalID_id=hos_id).values()
441
    )
442
    return JsonResponse({"doctors": doctorList})
1✔
443

444

445
def get_record(request, rec_id):
1✔
446
    healthRecordList = list(HealthRecord.objects.filter(id=rec_id).values())
1✔
447

448
    return JsonResponse({"data": json.dumps(healthRecordList[0], default=str)})
1✔
449

450

451
def get_edit(request, rec_id):
1✔
452
    selected_record = list(HealthRecord.objects.filter(id=rec_id).values())
1✔
453
    app = list(
1✔
454
        Appointment.objects.filter(id=selected_record[0]["appointmentId_id"]).values()
455
    )
456

457
    hospitalList = list(Hospital.objects.all().values())
1✔
458
    unselectedHospitalList = []
1✔
459
    for hospital in hospitalList:
1✔
460
        if hospital["id"] == selected_record[0]["hospitalID"]:
1✔
461
            selected_record[0]["hospital_name"] = hospital["name"]
1✔
462
        else:
463
            unselectedHospitalList.append(hospital)
×
464

465
    doctorList = list(HospitalStaff.objects.filter(admin=False).values())
1✔
466

467
    unselectedDoctorList = []
1✔
468
    for docs in doctorList:
1✔
469
        if docs["id"] == selected_record[0]["doctorID"]:
1✔
470
            selected_record[0]["doctor_name"] = docs["name"]
1✔
471
        else:
472
            unselectedDoctorList.append(docs)
×
473

474
    data = {
1✔
475
        "appointment_props": app[0],
476
        "record": selected_record[0],
477
        "hospitals": unselectedHospitalList,
478
        "appointmentType": APPOINTMENT_TYPE,
479
        "appointmentProps": json.dumps(APPOINTMENT_PROPS),
480
        "doctors": unselectedDoctorList,
481
    }
482

483
    return render(request, "edit_health_record.html", {"data": data})
1✔
484

485

486
@login_required
1✔
487
def add_health_record_view(request):
1✔
488
    hospitalList = list(Hospital.objects.all().values())
1✔
489
    data = {
1✔
490
        "hospitals": hospitalList,
491
        "appointmentType": APPOINTMENT_TYPE,
492
        "appointmentProps": json.dumps(APPOINTMENT_PROPS),
493
    }
494

495
    # Add hospital id to data if user is an admin
496
    try:
1✔
497
        hospital_staff = HospitalStaff.objects.get(userID=request.user.id)
1✔
498
        hospitalID = hospital_staff.hospitalID
1✔
499
        data["hospitalID"] = hospitalID.id
1✔
500
    except HospitalStaff.DoesNotExist:
1✔
501
        pass
1✔
502

503
    if request.method == "POST":
1✔
504

505
        medicalDocUrl = file_upload(request, "medicalHistory")
1✔
506
        hospitalID = request.POST.get("hospitalID")
1✔
507
        doctorID = request.POST.get("doctorId")
1✔
508
        userEmail = request.POST.get("userEmail")
1✔
509
        # update userID to be either request.user or the userID of the email provided by the admin
510
        # if userEmail is populated then get the user id of that email else it'll be request.user
511
        if userEmail:
1✔
512
            try:
×
513
                userID = User.objects.get(email=userEmail)
×
514
            except User.DoesNotExist:
×
515
                context = {
×
516
                    "error_message": "No patient exists with this email address. Please try again."
517
                }
518
                return render(request, "record_submit.html", context)
×
519
        else:
520
            userID = request.user
1✔
521
        # create a new appointment
522
        appointmentType = APPOINTMENT_TYPE[request.POST.get("appointmentType")]
1✔
523
        appointmentProperties = dict()
1✔
524
        all_fields = request.POST
1✔
525

526
        medicalDocs = {request.POST.get("appointmentType"): medicalDocUrl}
1✔
527
        for key, value in all_fields.items():
1✔
528
            if (
1✔
529
                key != "csrfmiddlewaretoken"
530
                and key != "hospitalID"
531
                and key != "doctorId"
532
                and key != "appointmentType"
533
            ):
534
                appointmentProperties[key] = value
1✔
535
        appointmentProperties = json.dumps(appointmentProperties)
1✔
536
        new_appointment = Appointment.objects.create(
1✔
537
            name=appointmentType, properties=appointmentProperties
538
        )
539
        appointmentID = new_appointment
1✔
540

541
        HealthRecord.objects.create(
1✔
542
            doctorID=doctorID,
543
            userID=userID,
544
            hospitalID=hospitalID,
545
            appointmentId=appointmentID,
546
            healthDocuments=medicalDocs,
547
        )
548
        return redirect("new_health_record_sent")
1✔
549
    return render(request, "record_submit.html", {"data": data})
1✔
550

551

552
@login_required
1✔
553
def edit_health_record_view(request):
1✔
554
    if request.method == "POST":
1✔
555
        rec = json.loads(request.body)
1✔
556
        id = rec.get("recordId")
1✔
557
        record = get_object_or_404(HealthRecord, id=id)
1✔
558
        appID = rec.get("appointmentId")
1✔
559
        appointment = get_object_or_404(Appointment, id=appID)
1✔
560

561
        appointment.name = APPOINTMENT_TYPE[rec.get("appointmentType")]
1✔
562
        appointment.properties = json.dumps(rec.get("appointmentProperties"))
1✔
563
        appointment.save()
1✔
564

565
        record.doctorID = rec.get("doctorId")
1✔
566
        record.hospitalID = rec.get("hospitalID")
1✔
567
        record.status = "pending"
1✔
568
        record.appointmentId = appointment
1✔
569
        record.save()
1✔
570

571
        return JsonResponse({"message": "Updated succesfully"})
1✔
572

573

574
def get_facility_doctors(request):
1✔
575
    if request.user.is_authenticated:
1✔
576
        user_hospital_staff_entry = get_object_or_404(
×
577
            HospitalStaff, userID=request.user.id
578
        )
579
        hospital_id = user_hospital_staff_entry.hospitalID.id
×
580

581
        staff_members = HospitalStaff.objects.filter(
×
582
            hospitalID=hospital_id, admin=False
583
        )
584

585
        staff_data = []
×
586
        for staff in staff_members:
×
587
            try:
×
588
                user = User.objects.get(id=staff.userID)
×
589
                staff_data.append(
×
590
                    {
591
                        "id": user.id,
592
                        "name": user.name,
593
                        "email": user.email,
594
                        "contactInfo": staff.contactInfo,
595
                        "specialty": staff.specialization,
596
                        "is_active": user.is_active,
597
                    }
598
                )
599
            except User.DoesNotExist:
×
600
                continue
×
601

602
        return JsonResponse({"data": staff_data}, safe=False)
×
603

604
    return JsonResponse({"error": "Unauthorized"}, status=401)
1✔
605

606

607
def get_facility_admins(request):
1✔
608
    if request.user.is_authenticated:
×
609
        user_hospital_staff_entry = get_object_or_404(
×
610
            HospitalStaff, userID=request.user.id
611
        )
612
        hospital_id = user_hospital_staff_entry.hospitalID.id
×
613

614
        staff_members = HospitalStaff.objects.filter(hospitalID=hospital_id, admin=True)
×
615

616
        staff_data = []
×
617
        for staff in staff_members:
×
618
            try:
×
619
                user = User.objects.get(id=staff.userID)
×
620
                staff_data.append(
×
621
                    {
622
                        "id": user.id,
623
                        "name": user.name,
624
                        "email": user.email,
625
                        "contactInfo": staff.contactInfo,
626
                        "specialty": staff.specialization,
627
                        "is_active": user.is_active,
628
                    }
629
                )
630
            except User.DoesNotExist:
×
631

632
                continue
×
633

634
        return JsonResponse({"data": staff_data}, safe=False)
×
635

636
    return JsonResponse({"error": "Unauthorized"}, status=401)
×
637

638

639
def hospital_staff_directory(request):
1✔
640
    context = {
×
641
        "get_facility_doctors_url": "api/get-facility-doctors/",
642
        "get_facility_admins_url": "api/get-facility-admins/",
643
    }
644
    return render(request, "healthcare_facility.html", context)
×
645

646

647
@login_required
1✔
648
@csrf_exempt
1✔
649
def add_healthcare_staff(request):
1✔
650
    if request.user.is_authenticated and request.method == "POST":
1✔
651
        email = request.POST.get("email")
1✔
652
        fullname = request.POST.get("fullname")
1✔
653
        contactInfo = request.POST.get("contactInfo")
1✔
654
        is_admin = int(request.POST.get("is_admin"))
1✔
655
        specialization = request.POST.get("specialization")
1✔
656

657
        user_hospital_staff_entry = get_object_or_404(
1✔
658
            HospitalStaff, userID=request.user.id
659
        )
660
        hospital_id = user_hospital_staff_entry.hospitalID.id
1✔
661

662
        context = {"error_message:": ""}
1✔
663

664
        if User.objects.filter(email=email).exists():
1✔
665
            user = User.objects.get(email=email)
1✔
666
            if user.is_patient:
1✔
667
                context["error_message"] = (
1✔
668
                    "A patient account already exists with this email"
669
                )
670
            elif user.is_staff:
1✔
671
                context["error_message"] = (
1✔
672
                    "An admin account already exists with this email"
673
                )
674
            else:
675
                context["error_message"] = (
1✔
676
                    "A healthcare worker account already exists with this email"
677
                )
678

679
            return render(request, "healthcare_facility.html", context)
1✔
680

681
        user_fields = {
1✔
682
            "email": email,
683
            "password": "dummy_password",  # healthcare worker will have to reset the password on first login
684
            "name": fullname,
685
            "contactInfo": contactInfo,
686
        }
687

688
        hospital = get_object_or_404(Hospital, id=hospital_id)
1✔
689

690
        user = None
1✔
691
        if is_admin:
1✔
692
            user = User.objects.create_staff(**user_fields)
1✔
693
        else:
694
            user = User.objects.create_healthcare_worker(**user_fields)
×
695

696
        HospitalStaff.objects.create(
1✔
697
            hospitalID=hospital,
698
            admin=is_admin,
699
            name=fullname,
700
            specialization=specialization,
701
            contactInfo=contactInfo,
702
            userID=user.id,
703
        )
704

705
        return redirect("hospital_staff_directory")
1✔
706

707
    return JsonResponse({"error": "Unauthorized"}, status=401)
×
708

709

710
@login_required
1✔
711
@csrf_exempt
1✔
712
def deactivate_healthcare_staff(request):
1✔
713
    if request.user.is_authenticated and request.method == "PUT":
1✔
714
        updated_data = json.loads(request.body)
1✔
715
        user_ids = updated_data.get("user_ids", [])
1✔
716

717
        for user_id in user_ids:
1✔
718
            user = get_object_or_404(User, id=user_id)
×
719
            if not user.is_patient:
×
720
                user.is_active = False
×
721
                user.save()
×
722

723
        return JsonResponse(
1✔
724
            {"message": "Healthcare staff deactivated successfully"}, status=200
725
        )
726

727
    return JsonResponse({"error": "Unauthorized"}, status=401)
×
728

729

730
@login_required
1✔
731
@csrf_exempt
1✔
732
def activate_healthcare_staff(request):
1✔
733
    if request.user.is_authenticated and request.method == "PUT":
1✔
734
        updatedData = json.loads(request.body)
1✔
735
        user_id = updatedData.get("user_id")
1✔
736

737
        user = get_object_or_404(User, id=user_id)
1✔
738

739
        if user.is_patient:
1✔
740
            return JsonResponse(
1✔
741
                {"error": "Patient's account cannot be edited"}, status=400
742
            )
743

744
        user.is_active = True
1✔
745
        user.save()
1✔
746
        return JsonResponse(
1✔
747
            {"message": "Healthcare staff activated successfully"}, status=200
748
        )
749

750
    return JsonResponse({"error": "Unauthorized"}, status=401)
×
751

752

753
@login_required
1✔
754
def community_home(request):
1✔
755
    return redirect("all_posts")
×
756

757

758
@login_required
1✔
759
def view_all_posts(request):
1✔
760
    posts = Post.objects.all().order_by("-createdAt")
1✔
761
    return render(
1✔
762
        request, "community_home.html", {"posts": posts, "headerTitle": "All the posts"}
763
    )
764

765

766
@login_required
1✔
767
def view_my_posts(request):
1✔
768
    posts = Post.objects.filter(user=request.user).order_by("-createdAt")
×
769
    return render(
×
770
        request, "community_home.html", {"posts": posts, "headerTitle": "My posts"}
771
    )
772

773

774
@login_required
1✔
775
def view_post(request, post_id):
1✔
776
    post = get_object_or_404(Post, id=post_id)
1✔
777
    comments = post.comments.all()
1✔
778
    return render(request, "post_details.html", {"post": post, "comments": comments})
1✔
779

780

781
@login_required
1✔
782
def create_post(request):
1✔
783
    if request.method == "POST":
1✔
784
        form = PostForm(request.POST)
1✔
785
        if form.is_valid():
1✔
786
            post = form.save(commit=False)
1✔
787
            post.user = request.user
1✔
788
            post.save()
1✔
789
            return redirect("community")
1✔
790
    else:
791
        form = PostForm()
×
792
    return render(request, "post_create.html", {"form": form})
×
793

794

795
@login_required
1✔
796
def edit_post(request, post_id):
1✔
797
    post = get_object_or_404(Post, id=post_id)
1✔
798
    if request.method == "POST":
1✔
799
        form = PostForm(request.POST, instance=post)
1✔
800
        if form.is_valid():
1✔
801
            form.save()
1✔
802
            return redirect("view_post", post_id=post.id)
1✔
803
    else:
804
        form = PostForm(instance=post)
×
805
    return render(request, "post_edit.html", {"form": form})
×
806

807

808
@login_required
1✔
809
def delete_post(request, post_id):
1✔
810
    post = get_object_or_404(Post, id=post_id)
1✔
811
    if request.method == "GET":
1✔
812
        post.delete()
1✔
813
        return redirect("community")
1✔
814
    return redirect("view_post", post_id=post_id)
×
815

816

817
@login_required
1✔
818
def create_comments(request, post_id):
1✔
819
    post = get_object_or_404(Post, id=post_id)
1✔
820
    if request.method == "POST":
1✔
821
        form = CommentForm(request.POST)
1✔
822
        if form.is_valid():
1✔
823
            comment = form.save(commit=False)
1✔
824
            comment.post = post
1✔
825
            comment.commenter = request.user
1✔
826
            comment.save()
1✔
827

828
    return redirect("view_post", post_id=post.id)
1✔
829

830

831
@login_required
1✔
832
def delete_comment(request, comment_id):
1✔
833
    comment = get_object_or_404(Comment, id=comment_id)
1✔
834
    if request.method == "GET":
1✔
835
        comment.delete()
1✔
836

837
    return redirect("view_post", post_id=comment.post.id)
1✔
838

839

840
@csrf_exempt
1✔
841
def request_health_history(request):
1✔
842
    if request.method == "POST":
1✔
843
        requestorName = request.POST.get("requestorName")
1✔
844
        requestorEmail = request.POST.get("requestorEmail")
1✔
845
        purpose = request.POST.get("purpose")
1✔
846
        userEmail = request.POST.get("userEmail")
1✔
847
        userDob = request.POST.get("dob")
1✔
848

849
        context = {"error_message:": ""}
1✔
850

851
        if not User.objects.filter(email=userEmail, dob=userDob).exists():
1✔
852
            context["error_message"] = "No user account exists with these details"
1✔
853
            return render(request, "request_health_history.html", context)
1✔
854

855
        user = User.objects.get(email=userEmail, dob=userDob)
1✔
856

857
        if not user.is_patient:
1✔
858
            context["error_message"] = "No user account exists with these details"
1✔
859
            return render(request, "request_health_history.html", context)
1✔
860

861
        HealthHistoryAccessRequest.objects.create(
1✔
862
            userID=user,
863
            requestorName=requestorName,
864
            requestorEmail=requestorEmail,
865
            purpose=purpose,
866
        )
867

868
        return redirect("homepage")
1✔
869

870
    return render(request, "request_health_history.html")
×
871

872

873
@login_required
1✔
874
@csrf_exempt
1✔
875
def view_health_history_access_requests(request):
1✔
876
    if request.method == "GET":
1✔
877
        user = request.user
1✔
878
        access_requests = HealthHistoryAccessRequest.objects.filter(
1✔
879
            userID=user
880
        ).order_by("-createdAt")
881
        return render(
1✔
882
            request, "view_access_requests.html", {"access_requests": access_requests}
883
        )
884

885
    return JsonResponse({"error": "wrong access method"}, status=401)
1✔
886

887

888
@login_required
1✔
889
@csrf_exempt
1✔
890
def update_health_history_access_request_status(request):
1✔
891
    if request.user.is_authenticated and request.method == "PUT":
1✔
892
        updatedData = json.loads(request.body)
1✔
893
        request_id = updatedData.get("request_id")
1✔
894
        status = updatedData.get("status")
1✔
895
        user_info = request.user
1✔
896

897
        request = get_object_or_404(HealthHistoryAccessRequest, id=request_id)
1✔
898

899
        request.status = status
1✔
900
        request.save()
1✔
901

902
        send_mail_response = 0
1✔
903

904
        if status == "approved":
1✔
905
            send_mail_response = send_mail(
1✔
906
                f"Update on Health History Access of: {user_info.name}",
907
                f"Hi {request.requestorName},\n\nYour request to access health history of {user_info.name} has been approved. Please find PDF report attached.\n\nRegards,\nHealth Score Team",
908
                "from@example.com",
909
                [request.requestorEmail],
910
            )
911
        else:
912
            send_mail_response = send_mail(
1✔
913
                f"Update on Health History Access of: {user_info.name}",
914
                f"Hi {request.requestorName},\n\nYour request to access health history of {user_info.name} has been rejected.\n\nRegards,\nHealth Score Team",
915
                "from@example.com",
916
                [request.requestorEmail],
917
            )
918

919
        message_response = ""
1✔
920
        if send_mail_response:
1✔
921
            message_response = "Email sent and request status updated successfully"
1✔
922
        else:
923
            message_response = (
1✔
924
                "Email could not be sent, but request status updated successfully"
925
            )
926

927
        return JsonResponse({"message": message_response}, status=200)
1✔
928

929
    return JsonResponse({"error": "Unauthorized"}, status=401)
1✔
930

931

932
@login_required()
1✔
933
def update_request_status(request):
1✔
934
    if request.method == "POST" and request.user.is_healthcare_worker:
1✔
NEW
935
        update = json.loads(request.body)
×
NEW
936
        record_id = update["recordID"]
×
NEW
937
        decision = update["status"]
×
UNCOV
938
        health_record = get_object_or_404(HealthRecord, id=record_id)
×
NEW
939
        if decision == "approved":
×
UNCOV
940
            health_record.status = "approved"
×
941
        else:
UNCOV
942
            health_record.status = "rejected"
×
NEW
943
            health_record.rejectedReason = update["reason"]
×
944

UNCOV
945
        health_record.save()
×
UNCOV
946
        return JsonResponse(
×
947
            {"message": "Request status updated successfully"}, status=200
948
        )
949

950
    return view_healthworkers_user_record(request)
1✔
951

952

953
@login_required
1✔
954
def view_healthworkers_user_record(request):
1✔
955
    if request.method == "GET" and request.user.is_healthcare_worker:
1✔
NEW
956
        current_user = request.user
×
NEW
957
        doc_id = HospitalStaff.objects.get(userID=current_user.id).id
×
NEW
958
        history_list = HealthRecord.objects.filter(doctorID=doc_id)
×
959

NEW
960
        appointment_name = request.GET.get("appointment_name")
×
NEW
961
        if appointment_name:
×
NEW
962
            history_list = history_list.filter(
×
963
                appointmentId__name__icontains=appointment_name
964
            )
965

NEW
966
        filter_date = request.GET.get("date")
×
NEW
967
        if filter_date:
×
NEW
968
            filter_date = datetime.strptime(filter_date, "%Y-%m-%d").date()
×
NEW
969
            current_tz = timezone.get_current_timezone()
×
NEW
970
            start_of_day = timezone.make_aware(
×
971
                datetime.combine(filter_date, datetime.min.time()), current_tz
972
            )
NEW
973
            end_of_day = start_of_day + timedelta(days=1)
×
NEW
974
            history_list = history_list.filter(
×
975
                createdAt__range=(start_of_day, end_of_day)
976
            )
977

NEW
978
        history_list = history_list.filter(status="pending")
×
979

NEW
980
        detailed_history_list = []
×
NEW
981
        each_details = []
×
NEW
982
        for h in history_list:
×
NEW
983
            h_details = model_to_dict(h)
×
NEW
984
            each_details.append(h_details)
×
985
            # Fetch related appointment details
NEW
986
            appointment_details = Appointment.objects.get(id=h.appointmentId_id)
×
NEW
987
            appointment_name = appointment_details.name
×
NEW
988
            appointment_properties = json.loads(h.appointmentId.properties)
×
NEW
989
            appointment_type = (
×
990
                appointment_details.name
991
                if appointment_details.name is not None
992
                else "Unknown"
993
            )
994

995
            # Fetch healthcare worker details by Dr. ID
NEW
996
            doctor_details = HospitalStaff.objects.get(id=h.doctorID)
×
NEW
997
            doctor_name = doctor_details.name
×
998

999
            # Fetch hospital details by hospitalID
NEW
1000
            hospital_details = Hospital.objects.get(id=h.hospitalID)
×
NEW
1001
            hospital_name = hospital_details.name
×
NEW
1002
            hospital_address = hospital_details.address
×
1003

NEW
1004
            user_email = User.objects.get(id=h.userID_id).email
×
1005
            # Append a dictionary for each record with all the details needed
NEW
1006
            detailed_history_list.append(
×
1007
                {
1008
                    "record_id": h.id,
1009
                    "user_id": user_email,
1010
                    "doctor_name": doctor_name,
1011
                    "hospital_name": hospital_name,
1012
                    "hospital_address": hospital_address,
1013
                    "createdAt": datetime.date(h.createdAt),
1014
                    "updatedAt": datetime.date(h.updatedAt),
1015
                    "appointment_name": appointment_name,
1016
                    "appointment_type": appointment_type,
1017
                    "record_status": h_details["status"],
1018
                    "appointment_properties": json.dumps(appointment_properties),
1019
                }
1020
            )
1021

NEW
1022
        zipped_details = detailed_history_list
×
1023
        # return zipped_details
NEW
1024
        return render(
×
1025
            request, "view_records_doctors.html", {"docs_records": zipped_details}
1026
        )
1027

1028
    return homepage(request)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc