File size: 16,171 Bytes
682caaf
 
 
 
 
 
 
 
 
 
 
 
 
f0d524c
682caaf
f0d524c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682caaf
 
 
 
 
 
 
 
 
 
f0d524c
682caaf
 
 
f0d524c
 
682caaf
 
 
f0d524c
682caaf
 
 
f0d524c
682caaf
 
f0d524c
682caaf
f0d524c
 
 
 
 
 
 
 
 
 
682caaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0d524c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682caaf
 
 
 
 
f0d524c
 
 
 
 
 
 
682caaf
 
 
 
 
 
 
f0d524c
 
 
 
 
 
682caaf
 
 
 
f0d524c
682caaf
 
 
f0d524c
 
682caaf
 
 
 
 
 
 
 
f0d524c
682caaf
 
 
f0d524c
 
682caaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
from datetime import datetime
from typing import List, Dict, Optional
from api.utils.fhir_client import HAPIFHIRClient
from db.mongo import db

class HAPIFHIRIntegrationService:
    """
    Service to integrate HAPI FHIR data with your existing database
    """
    
    def __init__(self):
        self.fhir_client = HAPIFHIRClient()
    
    def _validate_patient_data_completeness(self, patient: Dict, require_medical_data: bool = False) -> Dict[str, any]:
        """
        Validate if a patient has complete data
        
        Args:
            patient: Patient data dictionary
            require_medical_data: Whether to require medical data (observations, medications, conditions)
            
        Returns:
            Dict with validation results:
            {
                "is_complete": bool,
                "missing_fields": List[str],
                "has_medical_data": bool,
                "validation_score": float (0-1)
            }
        """
        required_demographic_fields = [
            'full_name', 'gender', 'date_of_birth', 'address'
        ]
        
        optional_demographic_fields = [
            'phone', 'email', 'marital_status', 'language'
        ]
        
        medical_data_fields = [
            'observations', 'medications', 'conditions'
        ]
        
        missing_fields = []
        validation_score = 0.0
        total_fields = len(required_demographic_fields) + len(optional_demographic_fields)
        present_fields = 0
        
        # Check required demographic fields
        for field in required_demographic_fields:
            value = patient.get(field, '')
            if not value or (isinstance(value, str) and value.strip() == ''):
                missing_fields.append(field)
            else:
                present_fields += 1
        
        # Check optional demographic fields
        for field in optional_demographic_fields:
            value = patient.get(field, '')
            if value and (not isinstance(value, str) or value.strip() != ''):
                present_fields += 1
        
        # Check medical data
        has_medical_data = False
        if 'clinical_data' in patient:
            clinical_data = patient['clinical_data']
            for field in medical_data_fields:
                if field in clinical_data and clinical_data[field]:
                    has_medical_data = True
                    break
        
        # Calculate validation score
        validation_score = present_fields / total_fields if total_fields > 0 else 0.0
        
        # Determine if patient is complete
        is_complete = len(missing_fields) == 0 and validation_score >= 0.7
        
        # If medical data is required, check if patient has it
        if require_medical_data and not has_medical_data:
            is_complete = False
            missing_fields.append('medical_data')
        
        return {
            "is_complete": is_complete,
            "missing_fields": missing_fields,
            "has_medical_data": has_medical_data,
            "validation_score": validation_score,
            "demographic_completeness": present_fields / len(required_demographic_fields + optional_demographic_fields) if (len(required_demographic_fields) + len(optional_demographic_fields)) > 0 else 0.0
        }
    
    async def import_patients_from_hapi(self, limit: int = 20, require_medical_data: bool = False, min_completeness_score: float = 0.7) -> dict:
        """
        Import patients from HAPI FHIR Test Server with data completeness validation
        
        Args:
            limit: Number of patients to fetch from HAPI FHIR
            require_medical_data: Whether to require patients to have medical data
            min_completeness_score: Minimum validation score (0-1) for a patient to be considered complete
        """
        try:
            print(f"Fetching {limit} patients from HAPI FHIR...")
            patients = self.fhir_client.get_patients(limit=limit)
            
            if not patients:
                print("No patients found in HAPI FHIR")
                return {
                    "imported_count": 0,
                    "skipped_count": 0,
                    "filtered_count": 0,
                    "total_found": 0,
                    "imported_patients": [],
                    "skipped_patients": [],
                    "filtered_patients": [],
                    "validation_summary": {},
                    "errors": []
                }
            
            print(f"Found {len(patients)} patients, checking for duplicates and data completeness...")
            
            imported_count = 0
            skipped_count = 0
            filtered_count = 0
            imported_patients = []
            skipped_patients = []
            filtered_patients = []
            errors = []
            validation_summary = {
                "total_processed": len(patients),
                "complete_patients": 0,
                "incomplete_patients": 0,
                "with_medical_data": 0,
                "without_medical_data": 0,
                "average_completeness_score": 0.0
            }
            
            total_completeness_score = 0.0
            
            for patient in patients:
                try:
                    # Check if patient already exists by multiple criteria
                    existing = await db.patients.find_one({
                        "$or": [
                            {"fhir_id": patient['fhir_id']},
                            {"full_name": patient['full_name'], "date_of_birth": patient['date_of_birth']},
                            {"demographics.fhir_id": patient['fhir_id']}
                        ]
                    })
                    
                    if existing:
                        skipped_count += 1
                        skipped_patients.append(patient['full_name'])
                        print(f"Patient {patient['full_name']} already exists (fhir_id: {patient['fhir_id']}), skipping...")
                        continue
                    
                    # Enhance patient data with additional FHIR data
                    enhanced_patient = await self._enhance_patient_data(patient)
                    
                    # Validate data completeness
                    validation_result = self._validate_patient_data_completeness(
                        enhanced_patient, 
                        require_medical_data=require_medical_data
                    )
                    
                    # Update validation summary
                    total_completeness_score += validation_result["validation_score"]
                    
                    if validation_result["has_medical_data"]:
                        validation_summary["with_medical_data"] += 1
                    else:
                        validation_summary["without_medical_data"] += 1
                    
                    # Check if patient meets completeness criteria
                    if not validation_result["is_complete"] or validation_result["validation_score"] < min_completeness_score:
                        filtered_count += 1
                        filtered_patients.append({
                            "name": patient['full_name'],
                            "fhir_id": patient['fhir_id'],
                            "missing_fields": validation_result["missing_fields"],
                            "completeness_score": validation_result["validation_score"],
                            "has_medical_data": validation_result["has_medical_data"]
                        })
                        print(f"Patient {patient['full_name']} filtered out - missing: {validation_result['missing_fields']}, score: {validation_result['validation_score']:.2f}")
                        validation_summary["incomplete_patients"] += 1
                        continue
                    
                    validation_summary["complete_patients"] += 1
                    
                    # Insert into database
                    result = await db.patients.insert_one(enhanced_patient)
                    
                    if result.inserted_id:
                        imported_count += 1
                        imported_patients.append({
                            "name": patient['full_name'],
                            "fhir_id": patient['fhir_id'],
                            "completeness_score": validation_result["validation_score"],
                            "has_medical_data": validation_result["has_medical_data"]
                        })
                        print(f"Imported patient: {patient['full_name']} (ID: {result.inserted_id}, Score: {validation_result['validation_score']:.2f})")
                    
                except Exception as e:
                    error_msg = f"Error importing patient {patient.get('full_name', 'Unknown')}: {e}"
                    errors.append(error_msg)
                    print(error_msg)
                    continue
            
            # Calculate average completeness score
            if validation_summary["total_processed"] > 0:
                validation_summary["average_completeness_score"] = total_completeness_score / validation_summary["total_processed"]
            
            print(f"Import completed: {imported_count} imported, {skipped_count} skipped, {filtered_count} filtered out")
            print(f"Validation summary: {validation_summary}")
            
            return {
                "imported_count": imported_count,
                "skipped_count": skipped_count,
                "filtered_count": filtered_count,
                "total_found": len(patients),
                "imported_patients": imported_patients,
                "skipped_patients": skipped_patients,
                "filtered_patients": filtered_patients,
                "validation_summary": validation_summary,
                "errors": errors
            }
            
        except Exception as e:
            print(f"Error importing patients: {e}")
            return {
                "imported_count": 0,
                "skipped_count": 0,
                "filtered_count": 0,
                "total_found": 0,
                "imported_patients": [],
                "skipped_patients": [],
                "filtered_patients": [],
                "validation_summary": {},
                "errors": [str(e)]
            }
    
    async def _enhance_patient_data(self, patient: Dict) -> Dict:
        """
        Enhance patient data with additional FHIR resources
        """
        try:
            patient_id = patient['fhir_id']
            
            # Fetch additional data from HAPI FHIR
            observations = self.fhir_client.get_patient_observations(patient_id)
            medications = self.fhir_client.get_patient_medications(patient_id)
            conditions = self.fhir_client.get_patient_conditions(patient_id)
            
            # Structure the enhanced patient data
            enhanced_patient = {
                # Basic demographics
                **patient,
                
                # Clinical data
                'demographics': {
                    'id': patient['id'],
                    'fhir_id': patient['fhir_id'],
                    'full_name': patient['full_name'],
                    'gender': patient['gender'],
                    'date_of_birth': patient['date_of_birth'],
                    'address': patient['address'],
                    'phone': patient.get('phone', ''),
                    'email': patient.get('email', ''),
                    'marital_status': patient.get('marital_status', 'Unknown'),
                    'language': patient.get('language', 'English')
                },
                
                'clinical_data': {
                    'observations': observations,
                    'medications': medications,
                    'conditions': conditions,
                    'notes': [],  # Will be populated separately
                    'encounters': []  # Will be populated separately
                },
                
                'metadata': {
                    'source': 'hapi_fhir',
                    'import_date': datetime.now().isoformat(),
                    'last_updated': datetime.now().isoformat(),
                    'fhir_server': 'https://hapi.fhir.org/baseR4'
                }
            }
            
            return enhanced_patient
            
        except Exception as e:
            print(f"Error enhancing patient data: {e}")
            return patient
    
    async def sync_patient_data(self, patient_id: str) -> bool:
        """
        Sync a specific patient's data from HAPI FHIR
        """
        try:
            # Get patient from HAPI FHIR
            patient = self.fhir_client.get_patient_by_id(patient_id)
            
            if not patient:
                print(f"Patient {patient_id} not found in HAPI FHIR")
                return False
            
            # Enhance with additional data
            enhanced_patient = await self._enhance_patient_data(patient)
            
            # Update in database
            result = await db.patients.update_one(
                {"fhir_id": patient_id},
                {"$set": enhanced_patient},
                upsert=True
            )
            
            if result.modified_count > 0 or result.upserted_id:
                print(f"Synced patient: {patient['full_name']}")
                return True
            else:
                print(f"No changes for patient: {patient['full_name']}")
                return False
                
        except Exception as e:
            print(f"Error syncing patient {patient_id}: {e}")
            return False
    
    async def get_patient_statistics(self) -> Dict:
        """
        Get statistics about imported patients
        """
        try:
            total_patients = await db.patients.count_documents({})
            hapi_patients = await db.patients.count_documents({"source": "hapi_fhir"})
            
            # Get sample patient data and convert ObjectId to string
            sample_patient = await db.patients.find_one({"source": "hapi_fhir"})
            if sample_patient:
                # Convert ObjectId to string for JSON serialization
                sample_patient['_id'] = str(sample_patient['_id'])
            
            stats = {
                'total_patients': total_patients,
                'hapi_fhir_patients': hapi_patients,
                'sample_patient': sample_patient
            }
            
            return stats
            
        except Exception as e:
            print(f"Error getting statistics: {e}")
            return {}
    
    async def get_hapi_patients(self, limit: int = 50) -> List[Dict]:
        """
        Get patients from HAPI FHIR without importing them
        """
        try:
            patients = self.fhir_client.get_patients(limit=limit)
            return patients
        except Exception as e:
            print(f"Error fetching HAPI patients: {e}")
            return []
    
    async def get_hapi_patient_details(self, patient_id: str) -> Optional[Dict]:
        """
        Get detailed information for a specific HAPI FHIR patient
        """
        try:
            patient = self.fhir_client.get_patient_by_id(patient_id)
            if not patient:
                return None
            
            # Get additional data
            observations = self.fhir_client.get_patient_observations(patient_id)
            medications = self.fhir_client.get_patient_medications(patient_id)
            conditions = self.fhir_client.get_patient_conditions(patient_id)
            
            return {
                'patient': patient,
                'observations': observations,
                'medications': medications,
                'conditions': conditions
            }
            
        except Exception as e:
            print(f"Error fetching patient details: {e}")
            return None