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

gcivil-nyu-org / Wednesday-Fall2023-Team-6 / 281

08 Nov 2023 08:37PM UTC coverage: 96.16%. First build
281

Pull #147

travis-pro

Chinnu1103
bucket name
Pull Request #147: Pre master - Check

1277 of 1328 new or added lines in 64 files covered. (96.16%)

1277 of 1328 relevant lines covered (96.16%)

0.96 hits per line

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

93.5
/hospital/views.py
1
from datetime import datetime, timedelta
1✔
2
from django.core.exceptions import ValidationError
1✔
3
from django.shortcuts import get_object_or_404
1✔
4
from django.http import HttpResponse, HttpResponseBadRequest
1✔
5
from django.views import generic
1✔
6
from .models import Hospital, HospitalAppointment
1✔
7
from user.models import Choices, Patient
1✔
8
from doctor.models import Doctor
1✔
9
from django.utils import timezone
1✔
10
import json
1✔
11
from django.core.paginator import Paginator
1✔
12
from .forms import HospitalFilterForm
1✔
13
from django.db.models import Q
1✔
14

15

16
class HospitalDetailView(generic.DetailView):
1✔
17
    model = Hospital
1✔
18
    template_name = "hospital/hospital_details.html"
1✔
19
    borough_converter = {}
1✔
20
    for borough in Choices.boroughs:
1✔
21
        borough_converter[borough[0]] = borough[1]
1✔
22

23
    def get(self, request, *args, **kwargs):
1✔
24
        return super().get(request, *args, **kwargs)
1✔
25

26
    def get_context_data(self, **kwargs):
1✔
27
        context = super(HospitalDetailView, self).get_context_data(**kwargs)
1✔
28

29
        try:
1✔
30
            context["object"].borough = self.borough_converter[
1✔
31
                context["object"].borough
32
            ]
NEW
33
        except Exception as e:
×
NEW
34
            print("Doctor Borough Exception: ", e)
×
35
        context["doctors"] = Doctor.objects.all().filter(
1✔
36
            associated_hospital=context["object"]
37
        )
38
        return context
1✔
39

40

41
class HospitalListView(generic.ListView):
1✔
42
    model = Hospital
1✔
43
    template_name = "hospital/hospital_list.html"
1✔
44

45
    # doctor list object name in html
46
    context_object_name = "hospital_list"
1✔
47

48
    def get_queryset(self):
1✔
49
        hospitals = Hospital.objects.all().order_by("name")
1✔
50
        filter_form = HospitalFilterForm(self.request.GET)
1✔
51

52
        """
1✔
53
        filter backend implementation
54
        """
55
        if filter_form.is_valid():
1✔
56
            name = filter_form.cleaned_data.get("name")
1✔
57
            facility_type = filter_form.cleaned_data.get("facility_type")
1✔
58
            location = filter_form.cleaned_data.get("location")
1✔
59
            borough = filter_form.cleaned_data.get("borough")
1✔
60
            postal_code = filter_form.cleaned_data.get("postal_code")
1✔
61

62
            if name:
1✔
63
                """
64
                to make the name contains the input name
65
                """
66
                hospitals = hospitals.filter(name__contains=name)
1✔
67
            if facility_type and facility_type != "All":
1✔
68
                hospitals = hospitals.filter(facility_type=facility_type)
1✔
69
            if location and location != "All":
1✔
70
                hospitals = hospitals.filter(location=location)
1✔
71
            if borough and borough != "All":
1✔
72
                hospitals = hospitals.filter(borough=borough)
1✔
73
            if postal_code and postal_code != "All":
1✔
74
                hospitals = hospitals.filter(postal_code=postal_code)
1✔
75

76
        return hospitals
1✔
77

78
    def get_context_data(self, **kwargs):
1✔
79
        context = super().get_context_data(**kwargs)
1✔
80

81
        """
1✔
82
        Pagination use the paginator to make pagination,
83
        which contains two variables,
84
        the first one is the context hospital list from get_queryset,
85
        the second one is the quantity of the page items.
86
        """
87
        paginator = Paginator(context["hospital_list"], 12)
1✔
88
        page_number = self.request.GET.get("page")
1✔
89
        hospital_list = paginator.get_page(page_number)
1✔
90
        context["hospital_list"] = hospital_list
1✔
91

92
        # Get filter parameters from the URL
93
        facility_type = self.request.GET.get("facility_type", "all")
1✔
94
        location = self.request.GET.get("location", "all")
1✔
95
        borough = self.request.GET.get("borough", "all")
1✔
96
        postal_code = self.request.GET.get("postal_code", "all")
1✔
97
        name = self.request.GET.get("name", "")
1✔
98
        context["filter_form"] = HospitalFilterForm(
1✔
99
            initial={
100
                "facility_type": facility_type,
101
                "location": location,
102
                "borough": borough,
103
                "postal_code": postal_code,
104
                "name": name,
105
            }
106
        )
107
        return context
1✔
108

109

110
def check_appointment_overlap(patient, appointment_dtime):
1✔
111
    end_time = appointment_dtime + timedelta(minutes=30)
1✔
112

113
    start_check = Q(start_time__lte=end_time)
1✔
114
    end_check = Q(start_time__gte=(appointment_dtime - timedelta(minutes=30)))
1✔
115
    overlapping_appointments = HospitalAppointment.objects.filter(
1✔
116
        start_check & end_check,
117
        patient=patient,
118
    )
119

120
    if overlapping_appointments.exists():
1✔
121
        return (True, "You have an overlapping appointment/request at that time")
1✔
122
    else:
123
        return (False, "")
1✔
124

125

126
def book_appointment(request, hospital_id):
1✔
127
    if request.method == "POST":
1✔
128
        if not request.user.is_authenticated:
1✔
129
            return HttpResponseBadRequest(
1✔
130
                "Cannot create an appointment without an account. Please Login!"
131
            )
132

133
        hospital = get_object_or_404(Hospital, pk=hospital_id)
1✔
134
        try:
1✔
135
            body = json.load(request)
1✔
136
            if Patient.objects.all().filter(email=request.user.username).exists():
1✔
137
                user = get_object_or_404(Patient, email=request.user.username)
1✔
138
            else:
NEW
139
                return HttpResponseBadRequest(
×
140
                    "You need to have a Patient account to create appointments!"
141
                )
142

143
            start_time = datetime.strptime(
1✔
144
                f'{body["date"]} {body["time"]}', "%Y-%m-%d %H:%M"
145
            )
146
            start_time = timezone.make_aware(start_time)
1✔
147

148
            overlap, overlap_message = check_appointment_overlap(user, start_time)
1✔
149
            if overlap:
1✔
NEW
150
                return HttpResponseBadRequest(overlap_message)
×
151

152
            preferred_doctor = None
1✔
153
            print(body["preferred_doctor"])
1✔
154
            if body["preferred_doctor"]:
1✔
155
                preferred_doctor = get_object_or_404(
1✔
156
                    Doctor, pk=int(body["preferred_doctor"])
157
                )
158

159
            name = body["name"]
1✔
160
            phone = body["phone"]
1✔
161
            email = body["email"]
1✔
162
            reason = body["reason"]
1✔
163
            accebility = body["accebility"]
1✔
164

165
        except Exception as e:
1✔
166
            print("Error: ", e)
1✔
167
            return HttpResponseBadRequest("Invalid Request")
1✔
168

169
        try:
1✔
170
            appointment = HospitalAppointment()
1✔
171
            appointment.patient = user
1✔
172
            appointment.hospital = hospital
1✔
173
            appointment.name = name
1✔
174
            appointment.phone = phone
1✔
175
            appointment.email = email
1✔
176
            appointment.reason = reason
1✔
177
            appointment.accebility = accebility
1✔
178
            appointment.start_time = start_time
1✔
179
            appointment.preferred_doctor = preferred_doctor
1✔
180
            appointment.status = "REQ"
1✔
181

182
            appointment.full_clean()
1✔
183
            appointment.save()
1✔
184
            print("Appointment Saved")
1✔
185
            return HttpResponse("Appointment Request Created Successfully!", status=200)
1✔
NEW
186
        except ValidationError as ve:
×
NEW
187
            print("Validation Error:", ve)
×
NEW
188
            return HttpResponseBadRequest(
×
189
                "Validation Error! Please ensure your details are correct"
190
            )
191

NEW
192
    return HttpResponseBadRequest("Invalid Request Method")
×
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