File size: 12,031 Bytes
6fd9abb
cda038b
6fd9abb
 
 
 
 
 
5dc9274
a70109e
5dc9274
a70109e
6fd9abb
 
cda038b
5dc9274
 
6fd9abb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a70109e
6fd9abb
04fbf57
6fd9abb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cda038b
6fd9abb
 
cda038b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fd9abb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cda038b
6fd9abb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dc9274
cda038b
 
 
 
 
 
a70109e
 
5dc9274
a70109e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dc9274
a70109e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dc9274
a70109e
 
 
8792a59
 
 
 
 
 
 
 
 
 
853f61b
8792a59
 
 
853f61b
8792a59
 
853f61b
8792a59
 
853f61b
8792a59
 
a70109e
8792a59
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
from rest_framework import views, response, status
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
import json
import os
from rest_framework.response import Response

# Added Appointment
from .models import UserProfile, TestResult, Appointment
# Added AppointmentSerializer
from .serializers import UserProfileSerializer, TestResultSerializer, AppointmentSerializer
from .ml_engine import predict_xray
from .storage import upload_to_supabase
from .pdf_generator import generate_medical_pdf 
# Added send_appointment_status_email
from .email_utils import send_html_email, get_medical_email_template, send_appointment_status_email

class UserProfileView(views.APIView):
    permission_classes = [IsAuthenticated]
    
    def post(self, request):
        user = request.user
        data = request.data
        profile, created = UserProfile.objects.get_or_create(user=user)
        
        current_role = str(profile.role).strip().lower() if profile.role else ""
        requested_role = data.get('role', 'patient').strip().lower()
        
        if current_role == 'doctor':
            pass 
        else:
            if requested_role == 'doctor':
                provided_code = data.get('access_code')
                secure_code = "e63ecb7857b348c5a79645c92578f5260defd2bde982bf823b8f66f5133fea52"
                
                if provided_code and str(provided_code).strip() == secure_code:
                    profile.role = 'doctor'
                else:
                    return response.Response(
                        {"error": "Invalid Access Code. Administrator privileges denied."}, 
                        status=status.HTTP_403_FORBIDDEN
                    )
            else:
                profile.role = 'patient'

        profile.state = data.get('state', '')
        profile.city = data.get('city', '')
        profile.age = data.get('age')
        profile.gender = data.get('gender', '')
        profile.license_number = data.get('licenseNumber', None)
        profile.full_name = data.get('full_name', '')
        profile.phone = data.get('phone', '')
        profile.address = data.get('address', '')
        
        profile.save()
        return response.Response(UserProfileSerializer(profile).data)

    def get(self, request):
        try:
            profile = request.user.profile
            return response.Response(UserProfileSerializer(profile).data)
        except UserProfile.DoesNotExist:
            return response.Response({"error": "Profile not found"}, status=404)

class PredictionView(views.APIView):
    permission_classes = [IsAuthenticated]
    
    def post(self, request):
        try:
            user_profile = request.user.profile
        except UserProfile.DoesNotExist:
            return response.Response({"error": "Complete profile first"}, status=400)

        image_file = request.FILES.get('file')
        symptoms = request.data.get('symptoms', '{}')
        
        if not image_file:
            return response.Response({"error": "No image provided"}, status=400)

        try:
            image_url = upload_to_supabase(image_file)
        except Exception as e:
            return response.Response({"error": f"Image upload failed: {str(e)}"}, status=500)
        
        image_file.seek(0)
        result, confidence, risk_level = predict_xray(image_file)
        
        test_record = TestResult.objects.create(
            patient=user_profile,
            xray_image_url=image_url,
            result=result,
            confidence_score=confidence,
            risk_level=risk_level,
            symptoms_data=json.loads(symptoms) if isinstance(symptoms, str) else symptoms
        )
        
        return response.Response(TestResultSerializer(test_record).data)

class EmailReportView(views.APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        try:
            if hasattr(request.user, 'profile') and request.user.profile.role == 'doctor':
                test_result = get_object_or_404(TestResult, pk=pk)
            else:
                test_result = get_object_or_404(TestResult, pk=pk, patient__user=request.user)
            
            pdf_buffer = generate_medical_pdf(test_result)
            
            patient_name = test_result.patient.full_name or request.user.username
            date_str = test_result.date_tested.strftime('%B %d, %Y')
            
            html_body = get_medical_email_template(
                patient_name=patient_name,
                test_date=date_str,
                risk_level=test_result.risk_level,
                confidence=round(test_result.confidence_score, 1)
            )

            send_html_email(
                subject=f"RespireX Screening Report - {date_str}",
                recipient_list=[request.user.email],
                html_content=html_body,
                pdf_buffer=pdf_buffer,
                filename=f"RespireX_Report_{test_result.id}.pdf"
            )

            return response.Response({"message": "Email sent successfully"})

        except Exception as e:
            print(f"Email Error: {e}")
            return response.Response({"error": "Failed to send email"}, status=500)

class PatientHistoryView(views.APIView):
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        try:
            profile = request.user.profile
            results = TestResult.objects.filter(patient=profile).order_by('-date_tested')
            return response.Response(TestResultSerializer(results, many=True).data)
        except UserProfile.DoesNotExist:
            return response.Response({"error": "Profile not found"}, status=404)
        except Exception as e:
            return response.Response({"error": str(e)}, status=500)

class DoctorDashboardView(views.APIView):
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        try:
            profile = request.user.profile
            if profile.role != 'doctor':
                return response.Response({"error": "Unauthorized"}, status=403)
        except UserProfile.DoesNotExist:
            return response.Response({"error": "Profile not found"}, status=404)
            
        state_filter = request.query_params.get('state', 'all')
        queryset = TestResult.objects.all().select_related('patient').order_by('-date_tested')
        
        if state_filter != 'all':
            queryset = queryset.filter(patient__state__iexact=state_filter)
            
        return response.Response({
            "doctor_name": profile.full_name,
            "stats": {
                "total": queryset.count(),
                "positive": queryset.filter(result='Positive').count(),
                "negative": queryset.filter(result='Negative').count(),
                "underReview": 0 
            },
            "records": TestResultSerializer(queryset, many=True).data
        })

class DownloadReportView(views.APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        try:
            if hasattr(request.user, 'profile') and request.user.profile.role == 'doctor':
                test_result = get_object_or_404(TestResult, pk=pk)
            else:
                test_result = get_object_or_404(TestResult, pk=pk, patient__user=request.user)
                
            pdf_buffer = generate_medical_pdf(test_result)
            
            filename = f"RespireX_Report_{test_result.id}.pdf"
            response = HttpResponse(pdf_buffer, content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="{filename}"'
            
            return response
            
        except Exception as e:
            return Response({"error": "Failed to generate report"}, status=500)

class PublicStatsView(views.APIView):
    permission_classes = [AllowAny] 

    def get(self, request):
        total_count = TestResult.objects.count()
        return response.Response({"total_tests": total_count})

# --- APPOINTMENT SYSTEM VIEWS ---

class DoctorListView(views.APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        doctors = UserProfile.objects.filter(role='doctor')
        return response.Response(UserProfileSerializer(doctors, many=True).data)

class AppointmentView(views.APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        try:
            profile = request.user.profile
            if profile.role == 'doctor':
                appointments = Appointment.objects.filter(doctor=profile).order_by('date_time')
            else:
                appointments = Appointment.objects.filter(patient=profile).order_by('date_time')
            
            return response.Response(AppointmentSerializer(appointments, many=True).data)
        except UserProfile.DoesNotExist:
            return response.Response({"error": "Profile not found"}, status=404)

    def post(self, request):
        try:
            patient_profile = request.user.profile
            doctor_id = request.data.get('doctor_id')
            date_time = request.data.get('date_time')
            reason = request.data.get('reason', '')

            if not doctor_id or not date_time:
                return response.Response({"error": "Doctor and Date are required"}, status=400)

            try:
                doctor_profile = UserProfile.objects.get(id=doctor_id, role='doctor')
            except UserProfile.DoesNotExist:
                return response.Response({"error": "Selected doctor not found"}, status=404)

            appointment = Appointment.objects.create(
                patient=patient_profile,
                doctor=doctor_profile,
                date_time=date_time,
                reason=reason,
                status='pending'
            )
            return response.Response(AppointmentSerializer(appointment).data, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            return response.Response({"error": str(e)}, status=400)

class AppointmentStatusView(views.APIView):
    permission_classes = [IsAuthenticated]

    def patch(self, request, pk):
        try:
            appointment = Appointment.objects.get(pk=pk)
            # Permission check
            if request.user.profile != appointment.doctor and request.user.profile != appointment.patient:
                return response.Response({"error": "Unauthorized"}, status=403)

            # --- THE FIX: USE SERIALIZER FOR UPDATES ---
            # This automatically handles string-to-date conversion and validation
            serializer = AppointmentSerializer(appointment, data=request.data, partial=True)
            
            if serializer.is_valid():
                updated_appt = serializer.save()
                
                # Send Email Notification
                if updated_appt.patient.user.email:
                    formatted_date = updated_appt.date_time.strftime('%B %d, %Y at %I:%M %p')
                    send_appointment_status_email(
                        recipient_email=updated_appt.patient.user.email,
                        patient_name=updated_appt.patient.full_name or "Patient",
                        doctor_name=updated_appt.doctor.full_name or "Doctor",
                        appointment_date=formatted_date,
                        status=updated_appt.status,
                        doctor_note=updated_appt.doctor_note
                    )
                
                return response.Response(serializer.data)
            
            return response.Response(serializer.errors, status=400)

        except Appointment.DoesNotExist:
            return response.Response({"error": "Appointment not found"}, status=404)
        except Exception as e:
            print(f"Appointment Update Error: {e}")
            return response.Response({"error": "Internal Error"}, status=500)